diff --git a/crates/transferd-overlay/src/session.rs b/crates/transferd-overlay/src/session.rs index 19190e8..87ad1d5 100644 --- a/crates/transferd-overlay/src/session.rs +++ b/crates/transferd-overlay/src/session.rs @@ -2085,6 +2085,43 @@ mod tests { ) } + /// The same link, with a switch: while `cut` is set, nothing written reaches the other end and nothing arrives + /// from it. That is what an unresponsive peer looks like from here: its acknowledgements never come. + fn switchable_link_pair( + id: u32, + cut: Arc, + ) -> (Arc, Arc) { + let a_to_b: Queue = Default::default(); + let b_to_a: Queue = Default::default(); + let end = |out: Queue, inbox: Queue, cut: Arc| { + let cut_write = cut.clone(); + Pipe { + write: Box::new(move |bytes| { + if !cut_write.load(Ordering::Relaxed) { + out.lock().push_back(bytes); + } + Ok(()) + }), + incoming: Box::new(move || { + if cut.load(Ordering::Relaxed) { + return Ok(None); + } + Ok(inbox.lock().pop_front()) + }), + close: Box::new(|| {}), + } + }; + ( + PipeLink::new( + id, + RouteKind::Direct, + "pipe", + end(a_to_b.clone(), b_to_a.clone(), cut.clone()), + ), + PipeLink::new(id, RouteKind::Direct, "pipe", end(b_to_a, a_to_b, cut)), + ) + } + fn setup(me: &NodeIdentity, peer: &NodeIdentity) -> SessionSetup { SessionSetup { peer_node_id: peer.node_id().to_string(), @@ -2248,11 +2285,24 @@ mod tests { SessionHandle, StreamId, mpsc::UnboundedReceiver, + ) { + let (route, phone_end) = link_pair(3); + open_stream_pair_over(route, phone_end).await + } + + /// The same pair, over the link ends given. + async fn open_stream_pair_over( + route: Arc, + phone_end: Arc, + ) -> ( + SessionHandle, + SessionHandle, + StreamId, + mpsc::UnboundedReceiver, ) { let desk_id = NodeIdentity::generate("desktop"); let phone_id = NodeIdentity::generate("phone"); let (desk_events_tx, mut desk_events) = mpsc::unbounded_channel(); - let (route, phone_end) = link_pair(3); let desk = spawn( setup(&desk_id, &phone_id), vec![route as Arc], @@ -2409,6 +2459,54 @@ mod tests { assert!(desk.recv(stream).await.is_err()); } + /// A close that cannot be flushed because the peer stopped answering gives up after `FLUSH_TIMEOUT`, and ends + /// the stream with a reset. The peer's reader must see that error once it is reachable again. A clean end here + /// would tell it the stream was complete when the bytes behind it were never acknowledged. + #[tokio::test] + async fn a_close_against_an_unresponsive_peer_resets_the_stream_instead_of_ending_it() { + let cut = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (route, phone_end) = switchable_link_pair(3, cut.clone()); + let (desk, phone, stream, _events) = open_stream_pair_over(route, phone_end).await; + + // The peer stops answering, and the desktop writes: nothing it sends can be acknowledged. + cut.store(true, Ordering::Relaxed); + desk.send(stream, b"never acknowledged".to_vec(), false) + .await + .expect("the write is queued"); + + // The close waits for the flush, which cannot finish while the peer is silent. It must give up on its own, + // after FLUSH_TIMEOUT, and not hang. + let started = tokio::time::Instant::now(); + desk.close(stream).await; + let waited = started.elapsed(); + assert!( + waited >= FLUSH_TIMEOUT, + "the close returned after {waited:?}, before the flush could have timed out" + ); + assert!( + waited < FLUSH_TIMEOUT + Duration::from_secs(5), + "the close took {waited:?}: it did not give up after FLUSH_TIMEOUT" + ); + + // The peer is reachable again. The reset is a control frame, so it is resent until the peer acknowledges it. + cut.store(false, Ordering::Relaxed); + let end = tokio::time::timeout(Duration::from_secs(15), async { + loop { + match phone.recv(stream).await { + // Bytes that made it through before the reset are read first. + Ok(Some(_)) => {} + other => return other.map(|_| ()), + } + } + }) + .await + .expect("the peer's reader gets an answer"); + assert!( + end.is_err(), + "the peer read a clean end of a stream that was never flushed: {end:?}" + ); + } + /// A route that refuses a frame must not stop the session. The frame goes out on the next /// live route, so both sides get their bytes, and the refusing route is tried first. #[tokio::test] diff --git a/crates/transferd-overlay/tests/relay_only.rs b/crates/transferd-overlay/tests/relay_only.rs index 42ab38d..416d143 100644 --- a/crates/transferd-overlay/tests/relay_only.rs +++ b/crates/transferd-overlay/tests/relay_only.rs @@ -184,15 +184,24 @@ async fn a_relay_that_stops_being_reachable_is_reported_not_hung() { stream.write_all(b"alive").await.expect("write"); assert_eq!(&read_exact(&mut stream, 6).await, b"\xE5alive"); - // When the relay is gone the session stops carrying traffic, and `overlay.peers` says so - // instead of the node pretending it is fine. + // When the relay is gone its route stops carrying traffic, and `overlay.peers` says so instead + // of the node pretending it is fine. + // + // The check is on the relayed route only. Both nodes are on loopback, so they can also + // hole-punch a direct UDP path while the test runs; that route is real, and once it is up it + // may carry the traffic. "Every route is down" is therefore not the property under test, and + // it was the cause of this test failing intermittently. relay.stop(); eventually("the relayed route to be reported down", || async { let peers = a.node.peer_list(); peers.len() == 1 && peers[0]["routes"] .as_array() - .map(|routes| !routes.is_empty() && routes.iter().all(|r| r["active"] == false)) + .map(|routes| { + let relayed: Vec<&serde_json::Value> = + routes.iter().filter(|r| r["kind"] == "relay").collect(); + !relayed.is_empty() && relayed.iter().all(|r| r["active"] == false) + }) .unwrap_or(false) }) .await; diff --git a/gui/README.md b/gui/README.md index 0dfc35e..6ef734d 100644 --- a/gui/README.md +++ b/gui/README.md @@ -12,7 +12,7 @@ Run these from this folder (`H:\Projects\Transferd\gui`). Packages are installed ``` python -m venv .venv -.venv\Scripts\python.exe -m pip install PySide6 cryptography blake3 pytest pyflakes +.venv\Scripts\python.exe -m pip install -r requirements.txt ``` ## Run @@ -43,9 +43,21 @@ The tests run offscreen (`QT_QPA_PLATFORM=offscreen` is set by `tests\conftest.p (`test_node_loopback.py`); - the service facade: start, settings saved and refused, failed actions logged and handed back (`test_service.py`); - every screen, offscreen, in an empty state and in a populated state where a real peer is connected, a file has moved and - an invite has been made (`test_qt_screens.py`). - -The relay tests need the built relay. Point `TRANSFERD_RELAYD` at it and they run; without it they are skipped: + an invite has been made (`test_qt_screens.py`); +- the debug protocol without a network: the wire format, the device policy, and the agent and client over in-memory + channels, with real shell commands, a real loopback forward and a real log process (`test_debug_protocol.py`); +- debugging between real nodes on 127.0.0.1: the device answers under its policy, consent for shell commands, forwards, + the device refusing unlisted computers, and the main claim: a second route joins the session and a log stream survives + the USB route being cut, with every line arriving once and in order (`test_debug_node.py`). The adb program is a fake + there, and the test says so; +- the Debug screen and the debugging settings, offscreen, with the real window and service (`test_debug_screen.py`); +- the wormhole (`test_wormhole_*.py`, described in `docs\WORMHOLE.md`): the codes and keys, the mailbox against the real + server, its limits and refusal codes, TLS and pins, the mailbox list, a hosted mailbox, the message checks, the folder archive and its safe unpacking, whole attempts in memory, the overlay transit on + loopback, the Wormhole screen with two real windows, and end-to-end runs with a cut connection, a cut route and the relay. + +The relay tests need the built relay (`test_node_loopback.py` and the relay case in `test_wormhole_e2e.py`). Point +`TRANSFERD_RELAYD` at it and they run; without it they are skipped. One wormhole relay test is an expected failure for a +known stall above about 1 MiB (see "Known limits" in `docs\WORMHOLE.md`): ``` set TRANSFERD_RELAYD=H:\Projects\Transferd\target\debug\relayd.exe @@ -64,11 +76,25 @@ Navigation is in the left sidebar, in five sections. registration counts, locate a peer); Peers (sessions, disconnect, accept incoming, dial a peer by address or through the relay); Invites (make an invite, copy it, check one, connect to its inviter). - **Transfer**: Transfer (send a file to a ready peer, open a stream and read its reply, accept or refuse incoming - requests, history); Hole punch (locate, with the start button disabled). + requests, history); Wormhole (send a file, a folder or a text with a short code, or type a code to receive it; needs a + mailbox, listed in Settings or hosted on this computer, and is disabled until there is one); Hole punch (locate, with the start button disabled). - **Tools**: DNS lookup (disabled); Ghost keys (create the key, load the issuer's key, make the request, finish with the answer, reset). +- **Debug**: Debugging. Choose the device (a connected peer, or paste its node id) and see its state. Connect a route over + Wi-Fi or USB; the routes it has are listed with their bytes. Ask the device for its information; start and stop its log, + with an optional filter; run a shell command with a time limit and see its output and exit code; forward a port to the + device; list every operation running now and stop one. Requests from computers wait here to be accepted or refused. - **System**: Events (the bounded log, filtered by level, clearable); Settings (every setting, validated; a value that - does not check out is refused with a message and nothing is saved). + does not check out is refused with a message and nothing is saved). Settings has two debugging groups: what listed + computers may do with this device (on/off, the list of computer ids, allow/ask/deny for each operation, forward ports, + the log command, the command limits), and this computer's side (the device to debug, transport, Wi-Fi address, adb + program, USB device port). A Wormhole group sets the mailboxes a wormhole meets on (a list, tried in order), whether this + computer hosts a mailbox and on which port, whether other computers may reach it, and how many data streams a wormhole + file uses (1 to 8). + +The debug protocol is specified in `docs\DEBUG_PROTOCOL.md`. It runs over the overlay's services `debug-info`, +`debug-logcat`, `debug-shell` and `debug-forward`, so it needs nothing from the relay or the library beyond sessions and +streams. Empty states say what is missing and what to do. Telemetry that has not been measured shows "no data yet"; no value is invented. @@ -108,3 +134,11 @@ These features are visible and disabled, each with the reason. The reasons are i window, so layout, colours and the look of the charts are unchecked. - The window was not driven by a person. Button clicks in the tests are programmatic. - The relay tests run only when `TRANSFERD_RELAYD` is set to a built `relayd.exe`. +- Wormhole: a relay transfer above about 1 MiB stalls (a known issue, see `docs\WORMHOLE.md`); the mailbox, its TLS and its hosting were tested only + on 127.0.0.1, with a self-made certificate; the Wormhole screen was driven by its buttons in tests, not by a person, and its file pickers were not + opened. +- Debugging has not been run with a real phone. No phone, cable or Android device was available. The Android agent + (an app that runs the device side on Android) is not built; the device side is this Python app, which runs on any + machine with Transferd. The USB route is tested with a fake adb program and with a second loopback connection that + stands in for `adb forward`. The real `adb forward` and the real cable were not exercised. +- The debug log and shell output were checked with commands on this computer, not on a device's real `logcat`. diff --git a/gui/docs/DEBUG_PROTOCOL.md b/gui/docs/DEBUG_PROTOCOL.md new file mode 100644 index 0000000..18d0b48 --- /dev/null +++ b/gui/docs/DEBUG_PROTOCOL.md @@ -0,0 +1,153 @@ +# Hybrid debugging over Transferd + +Status: version 1, implemented in `gui/transferd_gui/debug` (Python). The Android agent is not part of this build. + +## 1. What this is + +A way to debug a mobile device from a computer, built on Transferd's overlay. Debugging runs over authenticated, +encrypted Transferd sessions, and the same session can use a USB cable and Wi-Fi (or the relay) at once. When one +route goes away, the session carries on over the others, and the debugging streams keep running. + +It is not the Android Debug Bridge (ADB), and it does not speak ADB's wire format. It uses ADB only as one way to carry +a TCP connection over USB (`adb forward`). The rest is Transferd: + +| Concern | ADB | This protocol | +|---|---|---| +| Who may connect | An RSA key confirmed once on the device | A Transferd pairing (invite) plus an explicit allowlist of debugger node ids on the device | +| Encryption | None over TCP or USB | Every route is encrypted and authenticated (hybrid X25519 + ML-KEM, Ed25519 + ML-DSA) | +| Cable pulled out | The session drops and must be rebuilt by hand | Streams move to the Wi-Fi or relay route and continue | +| Per-operation control | All-or-nothing | Each operation (info, logcat, shell, forward) is allowed, asked for, or denied | +| Audit | None | Every operation is written to the device's event log, with the debugger's node id | + +## 2. Roles + +- **Client**: the debugging computer. It opens debug streams to a device and shows what comes back. +- **Agent**: the device. It answers debug streams, and enforces the policy below. Any Transferd node can be an agent; the + GUI node is one when "Allow debugging" is on in Settings. + +The roles are per node, so one node can be both. + +## 3. Routes and transports + +A debug session is one Transferd session to the device. Its routes are: + +- **Wi-Fi**: a direct connection to the device's listener, or the relay. Labelled by its address. +- **USB**: `adb forward tcp:L tcp:P` makes the device's listener (port `P`, on the device) reachable at `127.0.0.1:L` + on the computer. The client dials that address with the same handshake as any direct route, and adds it to the + session as a second route. Labelled `usb:`. + +Routes are attached to one session, so the overlay chooses between them by measured cost, and it resends unacknowledged +frames over a surviving route when one fails. A debug stream is an overlay stream, so it survives a route change without +the application noticing. + +The **transport mode** (Settings) decides which routes the client attaches: + +- `auto` (default): attach USB when the device is connected over USB, and keep Wi-Fi as well. Reattach USB after the + cable is plugged back in. +- `usb_only`: attach only USB. +- `wifi_only`: never run `adb`. + +## 4. Trust and consent + +Nothing is reachable by default. + +1. **Pairing.** The device and the computer must be paired by Transferd invite first. The handshake verifies the peer's + keys, so a debugger is always a known node. +2. **Debugger allowlist (device).** The device answers debug streams only from node ids in its `debug clients` list. + Any other node is refused with `denied`, whatever the per-operation modes say. +3. **Per-operation mode (device).** Each operation is one of: + - `allow`: run without asking; + - `ask`: the device's user accepts or refuses each stream in the app. A request nobody answers is refused when the + opener gives up (the overlay's open timeout); + - `deny`: always refused. + Defaults: `info` allow; `logcat`, `shell` and `forward` ask. +4. **Forward ports (device).** A forward is allowed only to a port in the device's `forward ports` list, and only to + `127.0.0.1` on the device. Empty list: no forwards. +5. **Shell.** Off unless `shell` is set to `allow` or `ask`. It runs the configured shell with the agent's own rights, + with a timeout and an output limit. There is no stdin. +6. **Audit.** Every stream the device gets, and its outcome, is written to the event log: who asked, which operation, + and whether it was allowed, asked for, refused or ended. + +## 5. Streams and messages + +Each operation is an overlay stream to a service named `debug-`, where `` is `info`, `logcat`, `shell` or +`forward`. The service names have no dots, so a Rust node can expose them too (its `expose` rejects dots). + +### 5.1 Request + +The client's first bytes on the stream are one JSON object and a newline: + +```json +{"v": 1, "args": {...}} +``` + +The request is at most 4096 bytes. `args` depends on the operation (section 5.2). Unknown keys in `args` are ignored. + +### 5.2 Operations + +| Operation | `args` | After `ok` | +|---|---|---| +| `info` | none | one `info` message, then the end | +| `logcat` | `filter` (text, optional) | `line` and `drop` messages until the client ends the stream | +| `shell` | `command` (text, required), `timeout` (seconds, optional, at most 600) | `out` messages, then one `exit` message, then the end | +| `forward` | `port` (1 to 65535) | raw bytes in both directions until either side ends | + +### 5.3 Responses + +Every operation begins with the agent's first message, which is either: + +- `{"t": "ok"}`: the operation was allowed and started; or +- `{"t": "error", "code": "", "text": ""}`, followed by the end of the stream. + +Later messages are one JSON object per line, with a `t` field: + +| `t` | Fields | Meaning | +|---|---|---| +| `info` | `props` (object) | Device properties: node name, node id, platform, Python version, protocol version, policy summary | +| `line` | `text` (string, at most 4096 characters; longer lines are cut) | One line of log output | +| `drop` | `count` (integer) | `count` lines were not sent because the client was not reading fast enough | +| `out` | `fd` (1 or 2), `b64` (base64 bytes) | Shell output | +| `exit` | `code` (integer or null), `reason` (`exited`, `timeout` or `output_limit`) | End of a shell command | +| `error` | `code`, `text` | The operation failed after it started | + +Receivers ignore messages with a `t` they do not know, and fields they do not know. That is how later versions add +things without breaking version 1. + +Error codes: `denied` (refused by the device's allowlist or by its user), `disabled` (debugging is off on the device), +`not_allowed` (a port or command outside the policy), `bad_request`, `unsupported_version`, `unavailable` (for example, +no log command is set on the device), `failed` (it could not start, for example the port refused the connection), +`too_many` (the client has too many streams open), `timeout`. + +### 5.4 Limits + +| Limit | Value | +|---|---| +| Request | 4096 bytes | +| One message line | 64 KiB | +| Shell command | 2048 bytes | +| Shell output | the device's `shell output limit` (default 256 KiB), then `exit` with `output_limit` | +| Shell time | the device's `shell timeout` (default 60 s), at most 600 s | +| Logcat queue | 1024 lines; more are dropped and counted in `drop` | +| Open streams per client | the device's `streams per client` (default 8) | + +## 6. Lifecycle + +1. The client opens `debug-` on the session. The device checks the client's node id, the operation's mode and + the arguments. It answers the open with allow, ask (pending in the device's app), or refuse. +2. If allowed, the agent sends `ok` and runs the operation. +3. The client may end the stream at any time. The agent stops the operation: a logcat reader stops, a shell command is + killed, and a forward closes its connection. +4. If the session loses every route, the streams end with an error, as any overlay stream does. Losing one route does + not end them. + +## 7. Versioning + +The request carries `v`. Version 1 is the only version. An agent that does not speak the version answers +`unsupported_version`. New operations are new services; new message types and fields are additive (section 5.3). + +## 8. Not in this build + +- The Android agent (an app that runs the device side). The agent in `gui/transferd_gui/debug/agent.py` runs on any + machine with Python and Transferd, which is enough to test the protocol and to act as a device on a computer. +- File sync, screenshots, and process lists. They fit the same pattern and are not built yet. +- Any use of the ADB server other than `adb devices` and `adb forward`. diff --git a/gui/docs/WORMHOLE.md b/gui/docs/WORMHOLE.md new file mode 100644 index 0000000..f977da4 --- /dev/null +++ b/gui/docs/WORMHOLE.md @@ -0,0 +1,455 @@ +# Transferd Wormhole + +Transferd Wormhole sends a file, a folder or a text from one computer to another with a short code. It is modelled on +magic-wormhole (https://github.com/magic-wormhole/magic-wormhole, MIT), and it is a separate protocol. It is not +wire-compatible with magic-wormhole: a code made by one program does not open the other. + +It takes the parts of magic-wormhole that work well (a short human code, a password-authenticated key exchange, a +rendezvous mailbox that holds encrypted messages, and a direct or relayed transfer) and builds the transfer on Transferd's +overlay. The overlay gives it what magic-wormhole's transit protocol does not have: post-quantum hybrid keys, several +routes at once with resends when one is cut, a relay that is Transferd's own, flow control, and identity checks on every +connection. + +The code lives in `gui\transferd_gui\wormhole\`. It is outside `python\`, so `scripts\sync-core.sh` does not copy it to +TransferDaemon. + +## What the user sees + +The screen is **Transfer → Wormhole** in the sidebar. + +- **Send**: choose a file, a folder or a text. The app shows a code such as `4217-ember-tundra-lattice`, with a copy + button. The receiver types it in. The screen then shows the state (for example "Waiting for the other computer to type + this code", "Sending") and the answer. +- **Receive**: type the code and press Look up. The app shows what is offered (name, size, kind, a text's length) and asks + Accept or Decline. Nothing is sent before Accept. A text is shown in the screen once received. +- **Stop or Cancel.** Cancelling a send ends it and the code stops working. Stopping while an offer waits declines it, so + the sender is told "stopped by the receiving user". +- **Mailbox.** The card at the top of the screen says where wormholes meet: the mailboxes listed in Settings, or this + computer's own mailbox when it is hosting one. If neither is set, the screen says so and every button is disabled. When + this computer hosts a mailbox on the network, the card shows its fingerprint and a **share line** to copy into the other + computer's Settings. + +The code is a secret for one transfer. After the transfer, a cancel, or a failed attempt, the code no longer works. + +## The code + +``` +4217-ember-tundra-lattice +``` + +- The first part is the **nameplate**, a decimal number from 1 to 65535. The mailbox allocates it at random. +- The rest are **three words** from the PGP word list (`wordlist.py`, copied from magic-wormhole's list, 256 pairs). + They carry 24 bits of secret. The word at position `i` is taken from the list for `i % 2`: even positions use the even + list and odd positions the odd list. A word that is missing, repeated or out of order fails the parity check, so a + dropped word is caught before any network is used. +- The code is normalised before use: lower case, spaces and underscores become `-`, and the nameplate must be digits. +- The password given to SPAKE2 is the normalised code as bytes, `b"4217-ember-tundra-lattice"`, so the nameplate is + inside the password. A mailbox cannot swap the nameplate without failing the exchange. + +Why three words and not two: magic-wormhole uses two. The mailbox cannot see right guesses from wrong ones, so the only +protection against guessing is the size of the secret. Three words make a guess 256 times harder, for one more word to +read out. + +## The mailbox + +The mailbox is a WebSocket server. It holds encrypted messages for a nameplate until both sides have read them. It never +sees a code, a key or a file. + +Settings → Wormhole holds the **mailbox list**: one or more addresses separated by commas, tried in the order given. There +is no public default. A wormhole needs a mailbox. It meets on this computer's own mailbox when the list is empty and +hosting is on (see "Hosting a mailbox on this computer" below). The two sides of a wormhole must reach the same mailbox. + +### Messages + +Every message is one JSON object in a WebSocket text frame. The mailbox protocol is version 2, which the `welcome` message +names. The wormhole's own protocol, the `version` phase below, is still version 1. The client sends these: + +| Message | Fields | Reply | +|---|---|---| +| `bind` | `appid` = `"transferd-wormhole/1"`, `side` (16 hex characters, random per attempt) | none | +| `allocate` | | `allocated` with `nameplate` | +| `claim` | `nameplate` | `claimed` with `mailbox` (32 hex characters), or `error` with `crowded` | +| `release` | `nameplate` | `released` | +| `open` | `mailbox` | the stored messages from the other side, then `opened`; new ones arrive as they are sent | +| `add` | `mailbox`, `id` (4 hex characters), `phase`, `body` (hex) | `added` with `id`, once stored; delivered to the other side as `message` | +| `ack` | `mailbox`, `id` | none; the message is then not replayed | +| `close` | `mailbox`, `mood` (`happy`, `lonely`, `errory`, `scary`) | `closed` | + +The server sends these: + +| Message | Fields | +|---|---| +| `welcome` | `protocol` (2), `limits`: `max_message_bytes` (65536), `max_messages_per_mailbox` (64), `bind_timeout_s` (30); sent first on every connection | +| `opened` | `mailbox`; sent after the stored messages of an `open` | +| `added` | `id`; a message is stored (also sent again for a retry of a stored message) | +| `allocated`, `claimed`, `released`, `closed` | the answers to `allocate`, `claim`, `release` and `close` | +| `message` | `mailbox`, `id`, `side` (the sender), `phase`, `body` | +| `error` | `code` (a machine-readable reason, see the table below), `error` (a short reason), `orig` (the message type it answers), `id` when it refuses one `add`, and `retry_after` (seconds) when trying again may succeed | + +Every refusal carries a `code`: + +| Code | Meaning | Retry | +|---|---|---| +| `bad_request` | a message is not a JSON object | no | +| `not_bound`, `already_bound`, `wrong_app`, `bad_side` | the bind was missing, repeated, for another app, or had a bad side id | no | +| `unknown_message` | a message type the mailbox does not know | no | +| `bad_nameplate`, `bad_id`, `bad_phase`, `bad_body`, `too_big` | a field has the wrong form or size | no | +| `no_mailbox` | the mailbox id is unknown, or this side is not in it | no | +| `crowded` | a third computer tried to claim a code | no | +| `full` | the mailbox holds as many messages as it allows | no | +| `no_nameplate` | no free nameplate could be found | after `retry_after` | +| `rate_limited` | this computer asked for too much, too fast | after `retry_after` | +| `busy` | the mailbox is at a cap, or the connection is over its limit | after `retry_after` | + +Rules the server keeps: + +- An unclaimed nameplate expires after 5 minutes. +- A nameplate has at most two sides. A third `claim` gets `crowded`. +- A mailbox expires after one hour with no traffic, or when both sides have sent `close`. +- A message the other side has not acknowledged is kept and sent again when that side opens the mailbox again. This is how + a dropped connection does not lose a message. +- The server never echoes a message to the side that sent it. +- A message over `max_message_bytes` is refused with `too_big`, and one past `max_messages_per_mailbox` with `full`. +- **Rate limits, per address.** Allocating a code: a burst of 30, then 30 a minute. Claiming: a burst of 120, then 2 a + second. Adding a message: a burst of 200, then 50 a second. A refusal says how long to wait. The limits are per address, + so computers behind one router share one allowance. +- **Caps.** At most 4096 nameplates, 1024 connections, and 64 connections from one address. Beyond these the mailbox + answers `busy` and closes the connection. +- **Idle connections.** A connection that has not bound within 30 seconds is closed. A connection that stops answering + pings is closed, so its nameplate is not held by a dead socket. + +### Running a mailbox + +``` +.venv\Scripts\python.exe -m transferd_gui.wormhole.server --host 127.0.0.1 --port 4470 +.venv\Scripts\python.exe -m transferd_gui.wormhole.server --host 0.0.0.0 --port 4470 --identity C:\path\to\folder +``` + +A mailbox that other computers can reach must be served over TLS. The second line does that: `--identity` names the folder +that holds its certificate and key, made on the first run. Without `--identity`, the server refuses any address other than +this computer's own. On start it prints the fingerprint to pin in the other computers' settings. + +It is meant to run on a server the user controls, or on this computer. The mailbox sees the nameplate, the side ids, the +phase names, the size and timing of each message, the mood of each close, and the IP address of each client. It does not +see the code, the keys or the content. + +### Addresses and the list + +An address is `wss://host:port#fingerprint` for another computer, or `ws://127.0.0.1:port` for this one. The port defaults +to 4470. + +- `wss://` is the only way to reach a mailbox on another computer. `ws://` is refused for any address other than + `127.0.0.1`, `localhost` or `::1`, so a plain connection never leaves the computer. +- The `#fingerprint` is the SHA-256 of the mailbox's certificate, 64 hex characters. It may be copied with spaces, colons + or dashes. It is never sent to the server: the client keeps it. +- A `wss://` address without a fingerprint is checked against the system's certificates, as a browser would check it. Use + this for a mailbox run with a certificate from a public authority. +- The list holds up to four addresses. It is tried in order, and the first that answers is used. + +### Certificates and pins + +A mailbox on the network serves `wss://` with a certificate this computer made for itself: an ECDSA P-256 key and a +certificate valid for ten years, kept in the wormhole folder. The certificate's fingerprint is the pin. Other computers are +given the pin with the address, and accept that certificate only. + +The check is made after the TLS handshake and before anything is sent. A different certificate is refused with a message +that names the mailbox and says to check the fingerprint. No nameplate, code or message leaves the computer. The handshake +still proves that the server holds the matching private key, so copying the certificate is not enough. + +The certificate is renewed when it is within 30 days of its end, or when its key does not match it. A renewal changes the +fingerprint, so the other computers must be given the new one. Keep the folder to keep the fingerprint. + +TLS keeps the nameplates, the timing, the sizes and the addresses from anyone on the network between the computers. The +messages are sealed by the two clients whatever the transport does. So a stranger who stood in for the mailbox could stop a +meeting, but could not read or change one. + +### Hosting a mailbox on this computer + +Settings → Wormhole → *Host a mailbox on this computer* starts a mailbox in the app, on the backend loop, on the port in +Settings (4470 by default). With it on: + +- With no list in Settings, wormholes on this computer meet on its own mailbox, at `ws://127.0.0.1:port`. +- With *Let other computers reach it* also on, the mailbox listens on every interface over `wss://`, pinned as above. The + Wormhole screen then shows the **share line**, `wss://:port#fingerprint`, with a button + to copy it. Other computers paste that line into their list in Settings. +- A port already in use is reported on the screen and in the event log. The app keeps running. +- Turning hosting off, or changing its port or its network setting, stops the server and starts it again with the new values. + +The first time the mailbox listens on the network, Windows Firewall may ask whether Python may accept connections. The +mailbox needs that allowed on the networks the other computers are on. + +### Connecting: retries and fallback + +- A connection is tried for each address in the list, in order, in up to three rounds. Between rounds the client waits a + growing time: half a second, doubling up to 8 seconds, randomised. If the mailbox asked for a longer wait (a busy mailbox + does), it waits up to 10 seconds. +- Once a mailbox has been reached, every later connection goes to that same mailbox. A reconnect never moves to another + one, because the two sides are meeting on the first. +- A request refused with `rate_limited` is sent again after the time the mailbox asked for, up to four times. A message + refused that way is sent again, rather than failing its caller. +- A connection the mailbox refuses as `busy` is tried again in the next round. + +The list helps when one mailbox is down for both computers. It cannot help when the two computers can reach different +mailboxes: each takes the first one it can reach, and they then wait on different servers. Keep the lists the same. + +## The key exchange + +Each wormhole attempt uses the same steps. Every step after `pake` is encrypted under keys that only the two sides can +make. + +1. **pake.** Both sides run SPAKE2 (`spake2` 0.9, symmetric, `idSymmetric = b"transferd-wormhole/1"`) with the code as + the password. Each sends its SPAKE2 message in plain: the message is public by design. Each side computes the same + shared secret `K`. +2. **Root key.** `root = blake3_derive_key("transferd-wormhole/1 root", K)`. +3. **Phase keys.** Each side has a random 16-hex-character `side`. The key a side uses to send in phase `P` is + `blake3_derive_key("transferd-wormhole/1 phase " + P, root + side)`. A side therefore has a different key from the other + side in every phase, so a message cannot be sent back to its sender and accepted there. +4. **Encryption.** AES-256-GCM (`cryptography`). The nonce is 12 random bytes and is sent with the message. The additional + authenticated data is `"transferd-wormhole/1" 0x00 side 0x00 phase 0x00 id`. A change to the side, the phase, or the + message id makes decryption fail. + +Every encrypted phase after `pake` is a JSON object, sealed as `nonce || ciphertext || tag`, in hex. + +**Key confirmation.** There is no separate verifier to read out. The `version` phase is the confirmation: if the codes +differ, the peer's `version` message will not decrypt, and the app reports "the code is wrong, or the message was +changed". This is the same result as an out-of-band check, with nothing extra for the user to do. + +### The phases + +Each phase is one message from each side, in this order: + +| Phase | Encrypted | Body | +|---|---|---| +| `pake` | no | the SPAKE2 message | +| `version` | yes | `{"protocol": 1, "app": "transferd-wormhole/1", "overlay": , "features": [...]}` | +| `identity` | yes | the sender's ephemeral identity and its places to be reached (below) | +| `offer` | yes | what is being sent (below). Only the sender sends it | +| `answer` | yes | `{"accept": true}` or `{"accept": false, "reason": "..."}`. Only the receiver sends it | +| `done` | yes | `{"ok": true, "sha256": "..."}` or `{"ok": false, "reason": "..."}`, sent after the transfer is checked | + +Both sides send `version` and `identity`. Each side refuses a `protocol` it does not speak, and refuses an `overlay` version +that does not match its own. + +### `identity` + +```json +{ + "node_id": "<64 hex characters>", + "public_key": "", + "name": "", + "relay": "", + "hints": [{"kind": "direct", "host": "192.168.1.5", "port": 53123}] +} +``` + +The identity is generated for this attempt only. The long-term node id is never sent, so a wormhole cannot be linked to +the computer's usual Transferd identity. The public key is sent under the phase keys, so the overlay can check that the +peer it connects to is the one that was named here (`expect_node_id`). + +### `offer` and `answer` + +```json +{"kind": "text", "text": "..."} +{"kind": "file", "name": "report.pdf", "size": 1234567, "sha256": ""} +{"kind": "directory", "name": "photos", "size": 9999, "sha256": "", "entries": 42} +``` + +A text is limited to 16 KiB of UTF-8, so it fits in one mailbox message and is never sent over the overlay. A folder is +sent as one zip archive, and the receiver unpacks it under a safe-name check described below. + +The receiver shows the offer and sends `answer`. Nothing is sent over the overlay before `accept`. A decline closes the +attempt, and the sender is told the reason. + +## Transit over the overlay + +Transit runs only for a file or a folder, after `accept`. The sender dials; the receiver serves. + +1. **Listen.** The receiver opens a TCP listener on an ephemeral port and lists its addresses as `hints`. If a relay is + set, it also registers its ephemeral identity there with `RelayHub` (token from `relay_token_for(node_id)`). Both + happen before `identity` is sent. +2. **Dial.** The sender dials every direct hint and, if the receiver names a relay, the relay, all at once. Each attempt + has 10 seconds. Each route that comes up is kept. A direct attempt completes the hybrid handshake with + `handshake_initiator(..., expect_node_id=...)` and checks the public key against the one in `identity`. +3. **Session.** Each connection becomes a `Link` (`TcpLink` for direct, `RelayLink` for the relay) and all of them go into one + `OverlaySession` (`spawn`). The session's services are `wormhole.control` and `wormhole.data`. The session must be up + within 15 seconds. +4. **Control stream.** The sender opens `wormhole.control` and writes one JSON line: + `{"kind", "name", "size", "sha256", "streams": N, "chunk": 262144}`. It must match the `offer` exactly, so the + receiver rejects a mismatch. +5. **Data streams.** The sender opens `N` streams of `wormhole.data` (default 4, at most 8). Chunk `i` of `chunk` bytes goes + to stream `i % N`. Each frame on a data stream is `offset (8 bytes, big-endian) | length (4 bytes) | payload`. Each + stream ends with the overlay's end-of-stream (FIN). The sender stays within 8 MiB of the progress the receiver reports. +6. **Check.** The receiver writes each frame at its offset into a file in a hidden staging folder inside the download + folder, and tracks which chunks have arrived. When all have arrived, it computes the SHA-256 of the whole file and + compares it with the `offer`. A file that does not match is removed and the transfer reports `ok: false`. A file that + matches is moved to a unique name in the download folder; a folder is unpacked from its checked archive. +7. **Done.** The receiver sends `done` with `ok` and the hash. The sender waits for it, then closes the session and the + mailbox (`close`, mood `happy`). + +### Using the overlay's features + +- **Several routes at once.** Every route that comes up joins one session, and the overlay spreads the data over them. The + overlay keeps counters per route (bytes sent, bytes sent again, round-trip time), exposed as + `OverlayTransit.route_reports()`. The Wormhole screen does not show them yet. +- **Failover.** If a route is cut in the middle of a transfer, the chunks still in flight on that route are sent again on + another one, and the transfer carries on from where it was. It does not start again from the beginning. This is tested + (see "Tests" below): a route is cut after both routes have carried data, the file arrives intact, and the counters show + bytes sent again. +- **No re-dial.** The sender dials once, when the transfer starts. A route that comes back later is not dialled again by + the sender. The receiver does accept new inbound routes into the same session. +- **Parallel streams.** Each stream has its own flow control, so one slow stream does not hold up the others. +- **Identity pinning.** A direct connection is refused unless the handshake's node id and public key are the ones named in + `identity` (tested with a stranger and a wrong node id). The relay path checks the same public key in `_dial_relay`; no + test yet forces a relay connection with a wrong key. +- **Post-quantum keys.** The overlay's keys come from its own hybrid handshake, not from the PAKE. So a future break of the + PAKE's discrete-log group would not expose the file contents recorded on the wire, although it could expose the + identities that were exchanged. + +### Limits + +| Limit | Value | +|---|---| +| Text | 16 KiB of UTF-8 | +| Mailbox message | 64 KiB (`max_message_bytes`); 64 messages per mailbox | +| Mailbox requests per address | allocate: 30 at once, then 30 a minute; claim: 120 at once, then 2 a second; add: 200 at once, then 50 a second | +| Mailbox caps | 4096 nameplates; 1024 connections; 64 connections from one address | +| Connection not bound | closed after 30 seconds | +| Mailbox list | up to 4 addresses, tried in order | +| Unclaimed nameplate | expires after 5 minutes | +| Idle mailbox | expires after 1 hour | +| Chunk | 256 KiB | +| Streams | 1 to 8 (default 4; set in Settings) | +| Data in flight | the sender stays within 8 MiB of the receiver's reported progress | +| Wait for the other side's `pake` | 60 s | +| Wait for `version`, `identity` and `offer` | 120 s each | +| Wait for accept or decline | 600 s | +| Dial each direct address, and the relay | 10 s each | +| Session up | 15 s | +| Receiver waits for the sender's connection after accepting | 300 s | +| Transfer with no data arriving | 120 s | +| Folder | 10,000 entries; 10 GiB unpacked; a compression ratio over 100 refused after the first MiB | + +## Folders and safe unpacking + +A folder is zipped to a temporary file before the offer. The receiver unpacks it only after the hash is checked, and it +refuses any archive that: + +- has an entry whose path is absolute, has a drive letter, or contains `..` after normalising; +- has a symbolic link, a device, or any entry that is not a file or a directory; +- has more entries than the offer named, more than 10,000 entries, or a total unpacked size over 10 GiB, or whose unpacked + size is more than 100 times its compressed size once the first MiB has been read. + +Unpacking writes into a new folder under the download folder, with a unique name. A failed unpack leaves nothing behind. + +## Deviations from magic-wormhole + +| Area | magic-wormhole | Transferd Wormhole | +|---|---|---| +| Wire compatibility | the reference | not compatible; its own appid and mailbox name | +| Code | 2 words | 3 words | +| Key derivation | HKDF over SHA-256 | BLAKE3 derive-key | +| Message encryption | NaCl SecretBox | AES-256-GCM with the side and phase in the additional data | +| Per-direction keys | one key per phase | one key per side per phase, so a message cannot be reflected | +| Verifier | a readable code to compare | none; the `version` phase is the confirmation | +| Identity | none (anonymous) | an ephemeral hybrid identity, sent under the phase keys | +| Transit | magic-wormhole's own relay and direct protocol | the Transferd overlay: hybrid handshake, several routes, resends, streams | +| Consent | the offer is shown, then accepted | the offer is shown, and nothing is sent before `accept` | +| Text | sent over the transit | sent in the mailbox, never over the transit | + +## Security + +- **Guessing the code.** The secret is 24 bits (three words). A guess is a live exchange on the nameplate. The mailbox can + count how many attempts ended with the mood `scary`, but it cannot tell which guess was wrong from the messages. A + nameplate takes at most two sides, and an unclaimed one expires after 5 minutes. A code is for one transfer. +- **Offline attacks.** SPAKE2 means a recorded exchange gives nothing to check guesses against. +- **The mailbox.** It can refuse, delay, drop or replay messages, but it cannot read or change them, because every message + is sealed with keys it does not have. A replay is caught by the message id and by the phase order. +- **The relay.** It sees encrypted overlay traffic and the node ids it registers. The relay token is derived from the node + id, as in the rest of Transferd. +- **Man in the middle.** Someone who sits between the two sides and does not know the code cannot pass `version`. Someone + who knows the code can be in the middle of the PAKE, but the code is then shared, and the attempt is the one the user + made. +- **Keys left behind.** Ephemeral identities and phase keys are kept in memory for one attempt. The attempt's identity is + not written to disk. +- **The mailbox's certificate.** Its private key sits in the wormhole folder, made owner-only where Windows allows it, and + otherwise under the folder's own permissions. The fingerprint is not secret: it is shown and shared on purpose. +- **Denial of service.** Rate limits and caps stop one computer, or a few, from filling a mailbox. They do not stop a large + number of addresses. A mailbox on the open internet should sit behind a firewall that limits who can reach it. +- **Plain connections.** The app never sends a message over a plain connection to another computer. A `ws://` address + other than this computer is refused when it is read, and again before connecting. +- **Downloads.** A received file has a unique name, is staged in a hidden folder until its hash is checked, and is never + placed outside the download folder. + +## Tests + +Run from `gui\`: + +``` +.venv\Scripts\python.exe -m pytest tests\test_wormhole_*.py -q +``` + +| File | What it covers | +|---|---| +| `test_wormhole_codes.py`, `test_wormhole_keys.py` | the code format, the word parity check, the key schedule, and AES-GCM with the side, phase and id bound | +| `test_wormhole_mailbox.py` | meeting on a nameplate, replay, acknowledgements, reconnection, limits, crowding, expiry (against the real server) | +| `test_wormhole_limits.py` | every refusal has its code; the rate limit and the time to wait; a client waits out a limit and carries on; a refused add is sent again; the connection, address and nameplate caps; the bind timeout | +| `test_wormhole_tls.py` | a pinned mailbox meets over `wss://`; a wrong pin is refused before anything is sent; a mailbox with no pin must have a certificate the system trusts; plain `ws://` to another computer is refused; the identity is kept, or made again when it no longer matches or is near its end; retries while a mailbox starts; a mailbox that is down is passed over; a reconnect stays on one mailbox; the command refuses the network without TLS | +| `test_wormhole_addresses.py` | the address and list rules, the defaults, the fingerprint forms, and each refusal with its reason | +| `test_wormhole_host.py` | the settings for the list and hosting; the hosted mailbox starts, stops, reports its state, serves `wss://` pinned to its own certificate, keeps its identity across restarts, and reports a port in use; a wormhole with no list meets on the hosted mailbox, end to end | +| `test_wormhole_protocol.py` | every message's fields, types and sizes; the versions that are refused | +| `test_wormhole_transfer.py` | the folder zip, the safe unpack (paths, links, entry and size limits) and the placing of files | +| `test_wormhole_session.py` | whole attempts with an in-memory transit: text, file, folder, decline, wrong code, timeouts, tampering | +| `test_wormhole_endpoint.py` | the overlay transit on 127.0.0.1: direct files, parallel streams with progress pacing, empty files, dial and identity checks | +| `test_wormhole_screen.py` | the Wormhole screen, offscreen, with two real windows and a real mailbox: a text sent and received; decline; stop while an offer waits; a wrong code on both sides; cancel and a new send; the mailbox card while hosting on this computer, on the network (fingerprint and share line), and after turning hosting off; a port in use; saving a bad mailbox list and the hosting choice in Settings | +| `test_wormhole_e2e.py` | a route cut mid-transfer (resends and completion); the mailbox connection cut before the other side arrives; a relay transfer (needs `TRANSFERD_RELAYD`) | + +The relay tests need the built relay. Set `TRANSFERD_RELAYD` to `relayd.exe` and they run; without it they are skipped. + +## Open decisions + +- **Mailbox default.** Magic-wormhole's public mailbox is a third party that would see every nameplate, so this build ships + with no public default. A wormhole needs a mailbox: one listed in Settings, or this computer's own when it hosts one. + Hosting in the app is the simple route for computers under one owner. A mailbox on a server the user controls is the + route for people who meet elsewhere. Defaulting to `wss://mailbox.magic-wormhole.io` would work out of the box, but it + gives a third party the metadata. +- **Relay.** The relay used for transit is the one in Settings, the same relay as the rest of the app. Files above about + 1 MiB through the relay do not complete yet; see "Known limits". + +## Known limits + +- **Large files over the relay stall.** With the receiver offering no direct address, a file through the relay completes + at 16 KiB, 65 KiB, 500 KiB and 1 MiB in about a second. At 1.5 MiB and 2 MiB it stops: the receiver gets no data after + the first burst, and the sender's route reports a loss of 1.0 and about 6 MB sent again. Cutting the relay's forwards in + flight from 128 to 8 did not change it. The cause is not found yet. The stall is on the relay path, in the library's + relay client or in `relayd`, not in the wormhole code. The reproduction is + `test_wormhole_e2e.py::test_a_file_of_two_mib_moves_through_the_relay`. It is marked as an expected failure with + `strict=True`, so when it is fixed the test fails until the mark is removed. +- **No route re-dial.** A route that is cut is not dialled again by the sender (see "Using the overlay's features"). +- **No progress bar or route table in the screen.** The screen shows the state, not the number of bytes sent. +- **No public default mailbox.** A wormhole does nothing until a mailbox is listed, or this computer hosts one. +- **The fallback needs the same reachability.** The two sides meet on the first mailbox each can reach. If one side can + reach a mailbox the other cannot, they wait on different servers and the meeting times out. +- **Shared rate limits.** Rate limits are per IP address, so computers behind one router share one allowance. On a busy + network a client can see `rate_limited`; it waits and carries on. +- **Hosting behind a router.** A hosted mailbox is reachable from the local network. Reaching it from the internet needs a + port forward on the router, which the app does not set up. +- **A renewed certificate changes the fingerprint.** The other computers must then be given the new one. The certificate is + renewed only near its end, or when its files are missing or do not match. +- **Not on the wide area.** Every test runs on 127.0.0.1. + +## Not verified + +- A real network with loss, reordering and a real cable: tests use loopback, and a proxy that cuts connections on purpose. +- A real wide-area mailbox: tests run the mailbox on 127.0.0.1. +- Relay transfers above about 1 MiB (the known stall above). +- A relay connection with a wrong public key (the check is in the code; no test forces it). +- The window's look, and a person using the screen: offscreen tests build the screen and drive its buttons, but do not show a + window, and the file pickers are not opened. +- The hosted mailbox across a real network: its tests bind to 127.0.0.1 through an injected address, so the bind to all + interfaces, the address in the share line, and the Windows Firewall prompt were not exercised. +- A `wss://` mailbox with a certificate from a public authority. The path is in the code, and a self-made certificate is + refused without a pin, but no test serves a publicly trusted certificate. +- A man in the middle. The pin check is tested with a fingerprint that the certificate does not match, not with an + attacker who intercepts the connection. +- The rate limits and caps under load. Tests set small limits and use one or two clients, not a crowd. +- A phone or any other device. diff --git a/gui/requirements.txt b/gui/requirements.txt new file mode 100644 index 0000000..435af9d --- /dev/null +++ b/gui/requirements.txt @@ -0,0 +1,13 @@ +# Everything the desktop app and its tests import, pinned to the versions the tests were run with. +# Install into the app's own venv only: +# python -m venv .venv +# .venv\Scripts\python.exe -m pip install -r requirements.txt +PySide6==6.12.0 +cryptography==50.0.2 +blake3==1.0.11 +# Wormhole: the SPAKE2 password-authenticated key exchange and the mailbox WebSocket client and server. +spake2==0.9 +websockets==17.4 +# Tests and checks. +pytest==9.2.0 +pyflakes==4.1.0 diff --git a/gui/tests/test_debug_node.py b/gui/tests/test_debug_node.py new file mode 100644 index 0000000..bd0eb16 --- /dev/null +++ b/gui/tests/test_debug_node.py @@ -0,0 +1,496 @@ +"""Debugging between real nodes. GUI nodes run in one process and talk over 127.0.0.1 through the library's own handshake, +sessions and streams. The device answers under its policy; the computer runs the operations. + +The USB route is a second loopback connection to the device's listener. That is what `adb forward` provides: the node +dials 127.0.0.1 and attaches the connection to the same session. The adb program itself is replaced by a fake in the adb +tests, which say so. Nothing here needs a phone or a cable. +""" + +from __future__ import annotations + +import asyncio +import re +import sys +import time +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Callable, Dict, List, Tuple + +import pytest + +from support import free_port, make_settings +from transferd_gui.backend.debugnode import policy_from_settings +from transferd_gui.backend.errors import NodeError +from transferd_gui.backend.node import Node +from transferd_gui.model.settings import SettingsError, updated + +PY = sys.executable +COMPUTER = "a" * 64 # a computer id that the device lists as a debugger +STRANGER = "f" * 64 # a valid id the device does not list +PORT_IN_DETAIL = re.compile(r"127\.0\.0\.1:(\d+)") + + +class EventLog: + """What a node wrote to its event log: a (level, source, text) entry per line.""" + + def __init__(self) -> None: + self.lines: List[Tuple[str, str, str]] = [] + + def __call__(self, level: str, source: str, text: str) -> None: + self.lines.append((level, source, text)) + + def has(self, level: str, fragment: str) -> bool: + return any(lvl == level and fragment in text for lvl, _, text in self.lines) + + +def make_node(folder: Path, **changes) -> Tuple[Node, EventLog]: + log = EventLog() + return Node(make_settings(folder, **changes), log), log + + +def computer_settings() -> Dict[str, object]: + """A computer dials out; it does not listen and does not use the relay.""" + return dict(allow_incoming=False, relay_address="") + + +def device_settings(computer_id: str, **changes) -> Dict[str, object]: + """A device that listens on a free port and answers `computer_id` for every debug operation.""" + base: Dict[str, object] = dict( + allow_incoming=True, + relay_address="", + listen_port=free_port(), + debug_enabled=True, + debug_clients=computer_id, + debug_info_mode="allow", + debug_logcat_mode="allow", + debug_shell_mode="ask", + debug_forward_mode="allow", + ) + base.update(changes) + return base + + +def script(folder: Path, name: str, body: str) -> str: + """Write a Python script and return the shell command that runs it with this interpreter.""" + folder.mkdir(parents=True, exist_ok=True) + path = folder / name + path.write_text(body, encoding="utf-8") + return f'"{PY}" "{path}"' + + +def printing_lines(folder: Path, count: int, delay: float = 0.0) -> str: + """A command that prints `line 0` … `line N-1`, one every `delay` seconds.""" + body = f"import time\nfor i in range({count}):\n print('line', i, flush=True)\n time.sleep({delay})\n" + return script(folder, f"lines_{count}_{int(delay * 1000)}.py", body) + + +def line_texts(messages: List[dict]) -> List[str]: + return [m["text"] for m in messages if m.get("t") == "line"] + + +async def until(predicate: Callable[[], bool], timeout: float = 10.0) -> bool: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if predicate(): + return True + await asyncio.sleep(0.02) + return predicate() + + +@asynccontextmanager +async def started(*nodes: Node): + for node in nodes: + await node.start() + try: + yield + finally: + for node in reversed(nodes): + await node.stop() + + +async def connect(computer: Node, device: Node) -> str: + """The computer dials the device's listener; returns once both ends report a ready session.""" + port = device.snapshot().listener.port + assert port is not None, "the device is not listening" + peer_id = await computer.dial_direct("127.0.0.1", port, expect_node_id=device.identity.node_id) + assert await until(lambda: bool(device.snapshot().ready_peers())) + return peer_id + + +def stream_for(node: Node, handle: int): + return next(s for s in node.snapshot().debug.streams if s.handle == handle) + + +# ----- the device answers, under its policy ------------------------------------------------------- + + +def test_a_listed_computer_reads_the_device_information(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id)) + async with started(device): + await connect(computer, device) + info = await computer.debug_info(device.identity.node_id) + return info, device.identity.name + + info, device_name = asyncio.run(scenario()) + assert info["node"] == device_name + assert info["protocol"] == 1 + assert info["platform"] == sys.platform + + +def test_a_computer_not_on_the_list_is_refused_and_the_device_logs_why(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, device_log = make_node(tmp_path / "device", **device_settings(STRANGER)) + async with started(device): + await connect(computer, device) + with pytest.raises(NodeError) as refused: + await computer.debug_info(device.identity.node_id) + return str(refused.value), device_log + + message, device_log = asyncio.run(scenario()) + assert "did not allow" in message + assert device_log.has("warning", "not on the device's list") + + +def test_a_device_with_debugging_off_does_not_offer_the_operations(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id, debug_enabled=False)) + async with started(device): + await connect(computer, device) + with pytest.raises(NodeError) as off: + await computer.debug_info(device.identity.node_id) + return str(off.value) + + assert "does not offer debugging" in asyncio.run(scenario()) + + +def test_logcat_streams_the_device_log_to_the_computer_in_order(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + command = printing_lines(tmp_path / "scripts", 5) + device, _ = make_node( + tmp_path / "device", + **device_settings(computer.identity.node_id, debug_log_command=command), + ) + async with started(device): + await connect(computer, device) + got: List[dict] = [] + handle = await computer.debug_logcat_start(device.identity.node_id, "line", got.append) + assert await until(lambda: len(line_texts(got)) >= 5, timeout=20) + await computer.debug_stop(handle) + return line_texts(got) + + assert asyncio.run(scenario()) == [f"line {i}" for i in range(5)] + + +def test_a_shell_command_runs_only_after_the_device_user_accepts_it(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id)) + async with started(device): + await connect(computer, device) + command = script(tmp_path / "scripts", "hi.py", "print('hi', 0)\n") + task = asyncio.create_task(computer.debug_shell(device.identity.node_id, command, 20.0)) + assert await until(lambda: any(r.service == "debug-shell" for r in device.snapshot().requests)) + await asyncio.sleep(0.3) + assert not task.done(), "the command ran before the device user accepted it" + request = next(r for r in device.snapshot().requests if r.service == "debug-shell") + await device.accept_request(request.request_id) + return await asyncio.wait_for(task, 20) + + result = asyncio.run(scenario()) + assert result["code"] == 0 + assert b"hi 0" in result["stdout"] + + +def test_a_shell_command_the_device_user_refuses_never_runs_and_is_reported_failed(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id)) + async with started(device): + await connect(computer, device) + marker = tmp_path / "ran.txt" + command = script(tmp_path / "scripts", "mark.py", f"open(r'{marker}', 'w').write('ran')\n") + task = asyncio.create_task(computer.debug_shell(device.identity.node_id, command, 20.0)) + assert await until(lambda: any(r.service == "debug-shell" for r in device.snapshot().requests)) + request = next(r for r in device.snapshot().requests if r.service == "debug-shell") + await device.refuse_request(request.request_id) + with pytest.raises(NodeError): + await asyncio.wait_for(task, 20) + shells = [s for s in computer.snapshot().debug.streams if s.kind == "shell"] + return shells, marker.exists(), device.snapshot().requests + + shells, marker_exists, pending = asyncio.run(scenario()) + assert not marker_exists, "the refused command ran" + assert pending == () + assert shells and shells[0].state == "failed", "the computer's Debug screen must not show a refused command as running" + + +def test_a_forward_carries_a_connection_to_a_port_on_the_device(tmp_path): + async def scenario(): + async def echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + data = await reader.read(100) + writer.write(b"echo:" + data) + await writer.drain() + writer.close() + + server = await asyncio.start_server(echo, "127.0.0.1", 0) + target = int(server.sockets[0].getsockname()[1]) + try: + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node( + tmp_path / "device", + **device_settings(computer.identity.node_id, debug_forward_ports=str(target)), + ) + async with started(device): + await connect(computer, device) + handle = await computer.debug_forward_start(device.identity.node_id, 0, target) + local = int(PORT_IN_DETAIL.search(stream_for(computer, handle).detail).group(1)) + reader, writer = await asyncio.open_connection("127.0.0.1", local) + writer.write(b"hello") + await writer.drain() + writer.write_eof() + reply = await asyncio.wait_for(reader.read(), 20) + writer.close() + await computer.debug_stop(handle) + return reply + finally: + server.close() + await server.wait_closed() + + assert asyncio.run(scenario()) == b"echo:hello" + + +def test_a_port_not_on_the_device_list_is_refused_and_the_reason_is_kept(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id, debug_forward_ports="9")) + async with started(device): + await connect(computer, device) + handle = await computer.debug_forward_start(device.identity.node_id, 0, 4444) + local = int(PORT_IN_DETAIL.search(stream_for(computer, handle).detail).group(1)) + reader, writer = await asyncio.open_connection("127.0.0.1", local) + reply = await asyncio.wait_for(reader.read(), 20) + writer.close() + note = stream_for(computer, handle).note + await computer.debug_stop(handle) + return reply, note + + reply, note = asyncio.run(scenario()) + assert reply == b"", "no bytes reach a port the device does not allow" + assert "forward list" in note + + +# ----- routes: the hybrid part -------------------------------------------------------------------- + + +def test_a_second_route_joins_the_session_and_a_log_stream_survives_losing_the_usb_route(tmp_path): + """The main claim: one session, two routes. A log stream runs over both; the USB route is cut in the middle; every line + still arrives, once and in order, over the route that is left.""" + + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + command = printing_lines(tmp_path / "scripts", 160, delay=0.03) + device, _ = make_node( + tmp_path / "device", + **device_settings(computer.identity.node_id, debug_log_command=command), + ) + async with started(device): + await connect(computer, device) + port = device.snapshot().listener.port + assert port is not None + # The USB route: a second loopback connection to the device's listener, as `adb forward` provides. + await computer.attach_route(device.identity.node_id, "127.0.0.1", port, label="usb:TESTSERIAL") + assert await until(lambda: any(len(s.routes) == 2 for s in computer.snapshot().sessions)) + labels = {r.label for r in computer.snapshot().sessions[0].routes} + + got: List[dict] = [] + handle = await computer.debug_logcat_start(device.identity.node_id, "line", got.append) + assert await until(lambda: len(line_texts(got)) >= 20, timeout=20) + + # Pull the cable. The test closes the USB link object directly; nothing else is touched. + usb = [link for link in computer._peers[device.identity.node_id].links if link.describe.startswith("usb:")] + assert len(usb) == 1 + usb[0].close() + + assert await until(lambda: len(line_texts(got)) >= 160, timeout=60) + await computer.debug_stop(handle) + states = [s.state for s in computer.snapshot().sessions] + return labels, line_texts(got), states + + labels, texts, states = asyncio.run(scenario()) + assert "usb:TESTSERIAL" in labels + assert texts == [f"line {i}" for i in range(160)], "every line arrived once, in order, across the route change" + assert states == ["ready"], "the session stayed up on the route that is left" + + +def test_a_device_takes_a_second_route_from_a_peer_it_already_has_a_session_with(tmp_path): + async def scenario(): + computer, _ = make_node(tmp_path / "computer", **computer_settings()) + async with started(computer): + device, _ = make_node(tmp_path / "device", **device_settings(computer.identity.node_id)) + async with started(device): + await connect(computer, device) + port = device.snapshot().listener.port + await computer.attach_route(device.identity.node_id, "127.0.0.1", port, label="wifi://second") + assert await until(lambda: any(len(s.routes) == 2 for s in device.snapshot().sessions)) + return [len(s.routes) for s in device.snapshot().sessions], len(device.snapshot().ready_peers()) + + route_counts, ready = asyncio.run(scenario()) + assert route_counts == [2], "the second connection became a route of the existing session, not a refusal" + assert ready == 1 + + +# ----- USB bridge, with a fake adb ---------------------------------------------------------------- + + +def fake_adb(folder: Path) -> Path: + """A stand-in for `adb`. It answers `devices`, `version` and `forward` (with or without `--remove`), and writes every + call to `calls.txt` in its folder. It forwards nothing: the real adb is not available to the tests, and the forward's + effect is covered by the loopback route tests.""" + folder.mkdir(parents=True, exist_ok=True) + calls = folder / "calls.txt" + body = ( + "import sys\n" + f"open({str(calls)!r}, 'a', encoding='utf-8').write(' '.join(sys.argv[1:]) + '\\n')\n" + "args = sys.argv[1:]\n" + "if args[:1] == ['devices']:\n" + " print('List of devices attached')\n" + " print('PHONE1234\\tdevice usb:1-1 product:x model:Pixel_8 device:x transport_id:1')\n" + " print('OLD9999\\tunauthorized usb:1-2 transport_id:2')\n" + "elif args[:1] == ['version']:\n" + " print('Android Debug Bridge version 1.0.41')\n" + "elif 'forward' in args:\n" + " print('')\n" + "else:\n" + " print('unknown command', file=sys.stderr)\n" + " sys.exit(1)\n" + ) + program = folder / "fake_adb.py" + program.write_text(body, encoding="utf-8") + if sys.platform == "win32": + launcher = folder / "adb.cmd" + launcher.write_text(f'@"{PY}" "{program}" %*\r\n', encoding="ascii") + else: + launcher = folder / "adb" + launcher.write_text(f'#!/bin/sh\nexec "{PY}" "{program}" "$@"\n', encoding="utf-8") + launcher.chmod(0o755) + return launcher + + +def test_usb_scan_reads_adb_devices_and_says_what_to_do_about_each(tmp_path): + adb = fake_adb(tmp_path / "adb") + + async def scenario(): + node, _ = make_node(tmp_path / "computer", **computer_settings(), usb_adb_path=str(adb)) + await node.start() + try: + devices = await node.debug_scan_usb() + return devices, node.debug_snapshot() + finally: + await node.stop() + + devices, snapshot = asyncio.run(scenario()) + assert [(d.serial, d.state, d.model) for d in devices] == [ + ("PHONE1234", "device", "Pixel 8"), + ("OLD9999", "unauthorized", ""), + ] + assert snapshot.usb_state == "ready", "one device is ready, so the bridge can use it" + assert "1 device(s) ready" in snapshot.usb_detail + assert len(snapshot.usb_devices) == 2 + assert "allow USB debugging" in devices[1].help, "the unauthorized phone says what to do" + + +def test_a_usb_forward_that_cannot_be_attached_is_removed_again(tmp_path): + adb = fake_adb(tmp_path / "adb") + + async def scenario(): + node, _ = make_node( + tmp_path / "computer", + **computer_settings(), + debug_device_id=COMPUTER, + usb_adb_path=str(adb), + usb_device_port=8022, + ) + await node.start() + try: + with pytest.raises(NodeError): + await node.debug_connect_usb("PHONE1234") # nothing listens on the forwarded port, so the attach fails + finally: + await node.stop() + + asyncio.run(scenario()) + calls = (tmp_path / "adb" / "calls.txt").read_text(encoding="utf-8").splitlines() + assert any(c.startswith("-s PHONE1234 forward tcp:") for c in calls) + assert any(c.startswith("forward --remove tcp:") for c in calls), "the forward was left behind" + + +def test_the_usb_bridge_waits_before_it_tries_again_after_a_failed_attach(tmp_path): + adb = fake_adb(tmp_path / "adb") + + async def scenario(): + node, log = make_node( + tmp_path / "computer", + **computer_settings(), + debug_device_id=COMPUTER, + usb_adb_path=str(adb), + usb_device_port=8022, + ) + await node.start() + try: + await node._usb_tick() + return node._usb_retry_at, log + finally: + await node.stop() + + retry_at, log = asyncio.run(scenario()) + assert retry_at > time.time(), "the bridge must not retry at once" + assert log.has("warning", "could not attach USB") + + +# ----- settings and policy ------------------------------------------------------------------------ + + +def test_debugging_settings_are_checked_before_they_are_used(tmp_path): + base = make_settings(tmp_path) + good = updated(base, {"debug_forward_ports": "8080, 5555", "debug_clients": COMPUTER, "debug_shell_mode": "allow"}) + assert good.debug_clients == COMPUTER + for bad in ( + {"debug_forward_ports": "99999"}, + {"debug_clients": "xyz"}, + {"debug_device_id": "short"}, + {"debug_transport": "satellite"}, + {"debug_shell_mode": "sometimes"}, + {"debug_wifi_address": "no-port"}, + {"usb_device_port": 70000}, + {"usb_adb_path": " "}, + {"debug_log_command": "bad\x01text"}, + ): + with pytest.raises(SettingsError): + updated(base, bad) + + +def test_the_device_policy_follows_the_settings(tmp_path): + settings = updated( + make_settings(tmp_path), + {"debug_enabled": True, "debug_clients": "b" * 64, "debug_forward_ports": "8080", "debug_shell_mode": "deny"}, + ) + policy = policy_from_settings(settings) + assert policy.enabled + assert policy.clients == frozenset({"b" * 64}) + assert policy.forward_ports == frozenset({8080}) + assert policy.mode("shell") == "deny" + assert policy.mode("logcat") == settings.debug_logcat_mode diff --git a/gui/tests/test_debug_protocol.py b/gui/tests/test_debug_protocol.py new file mode 100644 index 0000000..ec2a21c --- /dev/null +++ b/gui/tests/test_debug_protocol.py @@ -0,0 +1,464 @@ +"""The debug protocol without any network: the wire format, the policy, and the agent and client over in-memory channels. + +The operations run for real: shell commands are real processes, forwards reach a real loopback listener, and the log +source is a real process. Nothing is mocked except the device's identity, which is a fixed string. +""" + +from __future__ import annotations + +import asyncio +import json +import sys +from typing import AsyncIterator, List + +import pytest + +from transferd_gui.debug import agent as agent_mod +from transferd_gui.debug import wire +from transferd_gui.debug.agent import DebugAgent +from transferd_gui.debug.client import DebugClient, DebugError, bridge +from transferd_gui.debug.policy import DebugPolicy, check_modes, decide, parse_clients, parse_ports +from transferd_gui.debug.providers import SystemProviders +from transferd_gui.debug.stream import Channel, pipe_pair + +CLIENT = "c" * 64 +OTHER = "d" * 64 +PY = sys.executable + + +def run(coro): + return asyncio.run(coro) + + +def policy(**changes) -> DebugPolicy: + base = dict(enabled=True, clients=frozenset({CLIENT}), forward_ports=frozenset({9})) + base.update(changes) + return DebugPolicy(**base) + + +class Connection: + """A debugging computer and a device joined by in-memory channels. `open` plays the node's part: it makes the + device's end of a stream and hands the device's agent to serve it.""" + + def __init__(self, agent: DebugAgent, client_id: str = CLIENT) -> None: + self.agent = agent + self.client_id = client_id + self.tasks: List[asyncio.Task] = [] + + async def open(self, service: str) -> Channel: + op = wire.op_of(service) + assert op is not None, service + decision = self.agent.decide_open(op, self.client_id) + if decision.outcome == "refuse": + raise DebugError(decision.code, decision.reason) + mine, theirs = pipe_pair() + self.tasks.append(asyncio.create_task(self.agent.serve(op, self.client_id, theirs))) + return mine + + async def close(self) -> None: + for task in self.tasks: + task.cancel() + await asyncio.gather(*self.tasks, return_exceptions=True) + + +def make(providers=None, **changes): + audit: List[tuple] = [] + agent = DebugAgent(lambda: policy(**changes), providers or SystemProviders(node_name="device", node_id="e" * 64), lambda level, text: audit.append((level, text))) + return Connection(agent), audit + + +# ----- wire --------------------------------------------------------------------------------------- + + +def test_encode_is_one_line_of_json(): + data = wire.encode({"t": "line", "text": "héllo"}) + assert data.endswith(b"\n") and data.count(b"\n") == 1 + assert json.loads(data) == {"t": "line", "text": "héllo"} + + +def test_encode_refuses_a_message_over_its_limit(): + with pytest.raises(wire.WireError): + wire.encode({"t": "line", "text": "x" * 100}, limit=50) + + +def test_request_carries_version_and_args_and_respects_its_limit(): + line = wire.request({"filter": "x"}) + assert json.loads(line) == {"v": wire.PROTOCOL_VERSION, "args": {"filter": "x"}} + with pytest.raises(wire.WireError): + wire.request({"filter": "x" * (wire.MAX_REQUEST + 1)}) + + +def test_decoder_joins_pieces_and_keeps_bytes_after_the_first_line(): + decoder = wire.LineDecoder() + decoder.push(b'{"t":"ok"}\n{"t":"li') + assert decoder.take() == {"t": "ok"} + assert decoder.take() is None + decoder.push(b'ne"}\nRAW') + assert decoder.take_all() == [{"t": "line"}] + assert decoder.rest() == b"RAW" + + +def test_decoder_refuses_a_line_longer_than_its_limit(): + decoder = wire.LineDecoder(limit=16) + decoder.push(b"x" * 17) + with pytest.raises(wire.WireError): + decoder.take() + + +def test_decoder_refuses_something_that_is_not_json_or_not_an_object(): + decoder = wire.LineDecoder() + decoder.push(b"not json\n") + with pytest.raises(wire.WireError): + decoder.take() + decoder.push(b"[1, 2]\n") + with pytest.raises(wire.WireError): + decoder.take() + + +def test_service_names_have_no_dots_and_round_trip(): + for op in wire.OPS: + name = wire.service_name(op) + assert "." not in name + assert wire.op_of(name) == op + assert wire.op_of("file") is None + assert wire.op_of("debug-nothing") is None + with pytest.raises(wire.WireError): + wire.service_name("reboot") + + +def test_base64_round_trips_and_refuses_garbage(): + assert wire.unb64(wire.b64(b"\x00\xff bytes")) == b"\x00\xff bytes" + with pytest.raises(wire.WireError): + wire.unb64("!!not base64!!") + + +# ----- policy ------------------------------------------------------------------------------------- + + +def test_disabled_debugging_refuses_everything(): + decision = decide(policy(enabled=False), "info", CLIENT) + assert decision.outcome == "refuse" and decision.code == "disabled" + + +def test_a_computer_not_on_the_list_is_refused_whatever_the_mode(): + decision = decide(policy(modes={"info": "allow", "logcat": "allow", "shell": "allow", "forward": "allow"}), "shell", OTHER) + assert decision.outcome == "refuse" and decision.code == "denied" + + +def test_each_mode_maps_to_its_outcome(): + modes = {"info": "allow", "logcat": "ask", "shell": "deny", "forward": "ask"} + p = policy(modes=modes) + assert decide(p, "info", CLIENT).outcome == "allow" + assert decide(p, "logcat", CLIENT).outcome == "ask" + shell = decide(p, "shell", CLIENT) + assert shell.outcome == "refuse" and shell.code == "denied" + + +def test_default_policy_asks_before_logs_shell_or_forwards(): + p = DebugPolicy(enabled=True, clients=frozenset({CLIENT})) + assert decide(p, "info", CLIENT).outcome == "allow" + for op in ("logcat", "shell", "forward"): + assert decide(p, op, CLIENT).outcome == "ask", op + + +def test_ports_parse_and_refuse_bad_values(): + assert parse_ports("") == frozenset() + assert parse_ports("8080, 5555;9") == frozenset({8080, 5555, 9}) + for bad in ("0", "65536", "http", "80 80x"): + with pytest.raises(ValueError): + parse_ports(bad) + + +def test_clients_parse_and_refuse_bad_ids(): + assert parse_clients("") == frozenset() + assert parse_clients(CLIENT.upper()) == frozenset({CLIENT}) + with pytest.raises(ValueError): + parse_clients("abc") + with pytest.raises(ValueError): + parse_clients("z" * 64) + + +def test_check_modes_names_a_bad_mode(): + assert check_modes({"shell": "allow"}) == [] + assert check_modes({"shell": "sometimes"}) + + +# ----- agent and client, over channels ------------------------------------------------------------ + + +class ListLogs: + """A log source that yields the given lines, then ends.""" + + def __init__(self, lines: List[str]) -> None: + self.lines = lines + + def __call__(self, text_filter: str) -> AsyncIterator[str]: + async def gen(): + needle = text_filter.lower() + for line in self.lines: + if not needle or needle in line.lower(): + yield line + + return gen() + + +class NoLogs(SystemProviders): + def log_lines(self, text_filter: str): + return None + + +def test_info_reports_the_device_and_ends(): + async def scenario(): + connection, audit = make() + result = await DebugClient(connection.open).info() + await connection.close() + return result, audit + + result, audit = run(scenario()) + assert result["node"] == "device" + assert result["protocol"] == wire.PROTOCOL_VERSION + assert any("info answered" in text for _, text in audit) + + +def test_logcat_streams_the_lines_that_match_the_filter(): + async def scenario(): + providers = SystemProviders(node_name="device", node_id="e" * 64, log_command="") + providers.log_lines = ListLogs(["I tag: hello", "E tag: bad thing", "I other: fine"]) # type: ignore[method-assign] + connection, _audit = make(providers) + got: List[dict] = [] + await DebugClient(connection.open).logcat("tag", got.append) + await connection.close() + return got + + got = run(scenario()) + assert [m["text"] for m in got if m["t"] == "line"] == ["I tag: hello", "E tag: bad thing"] + + +def test_logcat_without_a_log_source_says_so(): + async def scenario(): + connection, _audit = make(NoLogs(node_name="device", node_id="e" * 64)) + try: + await DebugClient(connection.open).logcat("", lambda m: None) + except DebugError as exc: + return exc + finally: + await connection.close() + return None + + error = run(scenario()) + assert error is not None and error.code == "unavailable" + + +def test_logcat_drops_lines_the_client_does_not_read_and_says_how_many(): + async def scenario(): + providers = SystemProviders(node_name="device", node_id="e" * 64) + many = [f"line {i}" for i in range(agent_mod.LOG_QUEUE + 300)] + providers.log_lines = ListLogs(many) # type: ignore[method-assign] + connection, _audit = make(providers) + got: List[dict] = [] + + def slow(message: dict) -> None: + got.append(message) + + await DebugClient(connection.open).logcat("", slow) + await connection.close() + return got + + got = run(scenario()) + lines = [m for m in got if m["t"] == "line"] + drops = sum(m["count"] for m in got if m["t"] == "drop") + assert len(lines) + drops == agent_mod.LOG_QUEUE + 300 + + +def test_shell_runs_a_command_and_returns_its_output_and_code(): + async def scenario(): + connection, audit = make() + command = f'"{PY}" -c "import sys; print(\'hello from the device\'); sys.stderr.write(\'warn\'); sys.exit(3)"' + result = await DebugClient(connection.open).shell(command, 20.0) + await connection.close() + return result, audit + + result, audit = run(scenario()) + assert result["code"] == 3 and result["reason"] == "exited" + assert b"hello from the device" in result["stdout"] + assert b"warn" in result["stderr"] + assert any(level == "warning" and "shell" in text for level, text in audit) + + +def test_shell_stops_a_command_that_runs_past_its_timeout(): + async def scenario(): + connection, _audit = make() + command = f'"{PY}" -c "import time; time.sleep(60)"' + result = await DebugClient(connection.open).shell(command, 1.0) + await connection.close() + return result + + result = run(scenario()) + assert result["reason"] == "timeout" and result["code"] is None + + +def test_shell_stops_at_the_output_limit(): + async def scenario(): + connection, _audit = make(shell_output_limit=4096) + command = f'"{PY}" -c "import sys; sys.stdout.write(\'x\' * 200000)"' + result = await DebugClient(connection.open).shell(command, 20.0) + await connection.close() + return result + + result = run(scenario()) + assert result["reason"] == "output_limit" + assert len(result["stdout"]) <= 4096 + + +def test_a_forward_reaches_a_port_on_the_device_only_when_it_is_listed(): + async def scenario(): + async def echo(reader, writer): + data = await reader.read(100) + writer.write(data.upper()) + await writer.drain() + writer.close() + + server = await asyncio.start_server(echo, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + try: + connection, _audit = make(forward_ports=frozenset({port})) + channel, rest = await DebugClient(connection.open).forward(port) + await channel.write(b"hello") + await channel.end() + received = rest + while True: + chunk = await channel.read() + if chunk is None: + break + received += chunk + refused = None + try: + await DebugClient(connection.open).forward(port + 1) + except DebugError as exc: + refused = exc.code + await connection.close() + return received, refused + finally: + server.close() + await server.wait_closed() + + received, refused = run(scenario()) + assert received == b"HELLO" + assert refused == "not_allowed" + + +def test_a_forward_with_nothing_listening_fails_cleanly(): + async def scenario(): + connection, _audit = make(forward_ports=frozenset({9})) + try: + await DebugClient(connection.open).forward(9) + except DebugError as exc: + return exc.code + finally: + await connection.close() + return None + + assert run(scenario()) == "failed" + + +def test_an_unsupported_version_is_refused_with_its_code(): + async def scenario(): + connection, _audit = make() + channel = await connection.open(wire.service_name("info")) + await channel.write(b'{"v": 99, "args": {}}\n') + message = wire.LineDecoder() + got = None + while got is None: + chunk = await channel.read() + assert chunk is not None + messages = message.feed(chunk) + if messages: + got = messages[0] + await connection.close() + return got + + got = run(scenario()) + assert got["t"] == "error" and got["code"] == "unsupported_version" + + +def test_a_stream_with_no_request_is_refused_as_bad_request(): + async def scenario(): + connection, _audit = make() + channel = await connection.open(wire.service_name("shell")) + await channel.end() + decoder = wire.LineDecoder() + got = None + while got is None: + chunk = await channel.read() + if chunk is None: + break + messages = decoder.feed(chunk) + if messages: + got = messages[0] + await connection.close() + return got + + got = run(scenario()) + assert got is not None and got["code"] == "bad_request" + + +def test_too_many_streams_from_one_computer_are_refused(): + async def scenario(): + connection, _audit = make(streams_per_client=1) + agent = connection.agent + agent._active[CLIENT] = 1 # one stream already open + try: + await DebugClient(connection.open).info() + except DebugError as exc: + return exc.code + finally: + agent._active.pop(CLIENT, None) + await connection.close() + return None + + assert run(scenario()) == "too_many" + + +def test_bridge_carries_a_local_tcp_connection_over_a_forward(): + async def scenario(): + async def echo(reader, writer): + while True: + data = await reader.read(100) + if not data: + break + writer.write(data) + await writer.drain() + writer.close() + + device = await asyncio.start_server(echo, "127.0.0.1", 0) + port = device.sockets[0].getsockname()[1] + local_server = None + try: + connection, _audit = make(forward_ports=frozenset({port})) + client = DebugClient(connection.open) + done = asyncio.get_running_loop().create_future() + + async def accept(reader, writer): + channel, rest = await client.forward(port) + await bridge(reader, writer, channel, rest) + done.set_result(True) + + local_server = await asyncio.start_server(accept, "127.0.0.1", 0) + local_port = local_server.sockets[0].getsockname()[1] + reader, writer = await asyncio.open_connection("127.0.0.1", local_port) + writer.write(b"ping through the forward") + await writer.drain() + echoed = await asyncio.wait_for(reader.read(100), 10) + writer.write_eof() + await asyncio.wait_for(done, 10) + writer.close() + await connection.close() + return echoed + finally: + device.close() + await device.wait_closed() + if local_server is not None: + local_server.close() + await local_server.wait_closed() + + assert run(scenario()) == b"ping through the forward" diff --git a/gui/tests/test_debug_screen.py b/gui/tests/test_debug_screen.py new file mode 100644 index 0000000..900a08b --- /dev/null +++ b/gui/tests/test_debug_screen.py @@ -0,0 +1,236 @@ +"""The Debug screen and the debugging settings, offscreen, with the real window and service. The screen is checked against +snapshots that describe each state. One test runs a real action, asking an unconnected device for its information, through +the service, the node and the bridge back to the screen. +""" + +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path + +import pytest + +from test_qt_screens import build_window, empty_snapshot, pump +from transferd_gui.model.snapshot import ( + DebugSnapshot, + DebugStreamSnapshot, + IncomingRequest, + RouteSnapshot, + SessionSnapshot, + UsbDeviceSnapshot, +) + +COMPUTER = "c" * 64 +DEVICE = "d" * 64 + + +@pytest.fixture +def screens(qapp, tmp_path: Path): + window, service = build_window(qapp, tmp_path) + yield window, service, tmp_path + service.stop() + window.close() + window.deleteLater() + + +def snapshot_with(folder: Path, **parts): + return replace(empty_snapshot(folder / "snap"), **parts) + + +def connected_device(device_id: str, services, routes_up: bool = True) -> SessionSnapshot: + route = RouteSnapshot( + key="route-1", + peer_id=device_id, + link_id=1, + kind="direct", + up=routes_up, + closed=not routes_up, + label="usb:PHONE1234", + ) + return SessionSnapshot( + peer_id=device_id, + peer_name="phone", + state="ready", + version=1, + services=tuple(services), + routes=(route,), + established_at=0.0, + ) + + +# ----- the device side and the choice of device -------------------------------------------------- + + +def test_with_no_device_chosen_the_screen_says_so_and_the_device_is_off(screens): + window, _service, tmp = screens + window._on_snapshot(empty_snapshot(tmp / "empty")) + page = window.page("debug") + assert page.device_pill.text() == "no device chosen" + assert "Debugging is off on this device" in page.device_side.text() + + +def test_the_device_state_follows_the_session_to_this_device(screens): + window, service, tmp = screens + service.change_settings({"debug_device_id": DEVICE}) + page = window.page("debug") + + page.apply(snapshot_with(tmp / "none")) + assert page.device_pill.text() == "not connected" + + page.apply(snapshot_with(tmp / "noinfo", sessions=(connected_device(DEVICE, ["file", "stream"]),))) + assert page.device_pill.text() == "does not offer debugging" + + page.apply(snapshot_with(tmp / "down", sessions=(connected_device(DEVICE, ["debug-info"], routes_up=False),))) + assert page.device_pill.text() == "no live route" + + page.apply(snapshot_with(tmp / "ready", sessions=(connected_device(DEVICE, ["debug-info", "debug-shell"]),))) + assert page.device_pill.text() == "ready" + assert page.routes.row_count() == 1 + assert page.routes.cell(0, 0) == "usb:PHONE1234" + + +def test_a_typed_device_id_is_saved_and_a_bad_one_is_refused(screens): + window, service, _tmp = screens + page = window.page("debug") + + page.device_edit.setText("xyz") + page._use_device() + assert "64 lowercase hex" in page.choice_notice.text() + assert service.settings.debug_device_id == "" + + page.device_edit.setText(DEVICE.upper()) + page._use_device() + assert service.settings.debug_device_id == DEVICE, "the id is saved in lowercase" + + +def test_actions_that_need_a_device_say_to_choose_one_first(screens): + window, _service, _tmp = screens + page = window.page("debug") + page._ask_info() + assert "Choose the device first" in page.choice_notice.text() + + +# ----- the lists ----------------------------------------------------------------------------------- + + +def test_requests_list_only_debug_requests_and_accept_is_enabled_for_them(screens): + window, _service, tmp = screens + requests = ( + IncomingRequest(7, COMPUTER, "laptop", "debug-shell", 1_700_000_000.0), + IncomingRequest(8, COMPUTER, "laptop", "file", 1_700_000_001.0), + ) + page = window.page("debug") + page.apply(snapshot_with(tmp / "requests", requests=requests)) + assert page.requests.row_count() == 1 + assert page.requests.cell(0, 1) == "shell" + assert page._request_ids == [7] + assert page.accept_button.isEnabled() + + +def test_operations_list_shows_each_stream_with_its_state_and_note(screens): + window, _service, tmp = screens + streams = ( + DebugStreamSnapshot(1, DEVICE, "logcat", "all lines", 0.0, "running", ""), + DebugStreamSnapshot(2, DEVICE, "forward", "127.0.0.1:5000 -> device port 9", 0.0, "failed", "port 9 is not on this device's forward list"), + ) + page = window.page("debug") + page.apply(snapshot_with(tmp / "streams", debug=DebugSnapshot(agent_enabled=True, streams=streams))) + assert page.streams.row_count() == 2 + assert page.streams.cell(0, 0) == "logcat" + assert page.streams.cell(1, 3) == "failed" + assert "forward list" in page.streams.cell(1, 4) + assert page.stop_stream.isEnabled() + + +def test_usb_list_tells_the_user_what_to_do_about_each_phone(screens): + window, _service, tmp = screens + usb = (UsbDeviceSnapshot("PHONE1234", "device", "Pixel 8"), UsbDeviceSnapshot("OLD9999", "unauthorized", "")) + page = window.page("debug") + page.apply(snapshot_with(tmp / "usb", debug=DebugSnapshot(usb_state="ready", usb_devices=usb, usb_detail="1 device(s) ready over USB"))) + assert page.usb_table.row_count() == 2 + assert page.usb_table.cell(0, 3) == "ready" + assert "allow USB debugging" in page.usb_table.cell(1, 3) + + +def test_a_selected_row_survives_an_update_with_the_same_rows(screens): + window, _service, tmp = screens + streams = ( + DebugStreamSnapshot(1, DEVICE, "logcat", "all lines", 0.0, "running", ""), + DebugStreamSnapshot(2, DEVICE, "shell", "hi", 0.0, "running", ""), + ) + page = window.page("debug") + snap = snapshot_with(tmp / "stable", debug=DebugSnapshot(agent_enabled=True, streams=streams)) + page.apply(snap) + page.streams.table.selectRow(1) + page.apply(snap) + assert page.streams.selected_row() == 1, "a once-a-second update must not clear the user's selection" + + +# ----- the log, the shell, forwarding ------------------------------------------------------------- + + +def test_log_lines_drops_and_errors_reach_the_screen(screens): + window, _service, _tmp = screens + page = window.page("debug") + page._on_log_message({"t": "line", "text": "hello from the device"}) + page._on_log_message({"t": "drop", "count": 3}) + assert "hello from the device" in page.log_view.toPlainText() + assert "3 lines skipped" in page.log_view.toPlainText() + page._on_log_message({"t": "error", "text": "boom"}) + assert page.log_notice.text() == "boom" + + +def test_a_shell_result_shows_its_output_and_exit_code(screens): + window, _service, _tmp = screens + page = window.page("debug") + page._shell_done(True, {"code": 0, "reason": "", "stdout": b"hi 0\n", "stderr": b"warn\n"}) + assert "hi 0" in page.shell_output.toPlainText() + assert "--- stderr ---" in page.shell_output.toPlainText() + assert page.shell_notice.text() == "Finished: exit code 0 (finished)." + + +# ----- a real action through the service and the node ---------------------------------------------- + + +def test_asking_an_unconnected_device_reports_it_through_the_real_node(screens, qapp): + window, service, _tmp = screens + service.change_settings({"debug_device_id": DEVICE}) + service.start() + try: + page = window.page("debug") + page._ask_info() + assert pump(qapp, lambda: "Asking the device" not in page.choice_notice.text(), timeout=20) + assert "not connected" in page.choice_notice.text() + finally: + service.stop() + + +# ----- settings ------------------------------------------------------------------------------------ + + +def test_the_debugging_settings_are_saved_together(screens): + window, service, _tmp = screens + page = window.page("settings") + page.debug_enabled.setChecked(True) + page.debug_clients.setText(COMPUTER) + page.mode_boxes["shell"].setCurrentIndex(page.mode_boxes["shell"].findData("deny")) + page.debug_forward_ports.setText("8080, 5555") + page.debug_shell_timeout.setValue(90.0) + page._save() + saved = service.settings + assert saved.debug_enabled is True + assert saved.debug_clients == COMPUTER + assert saved.debug_shell_mode == "deny" + assert saved.debug_forward_ports == "8080, 5555" + assert saved.debug_shell_timeout_s == 90.0 + + +def test_an_invalid_debugging_setting_is_refused_and_nothing_is_saved(screens): + window, service, _tmp = screens + page = window.page("settings") + page.debug_enabled.setChecked(True) + page.debug_clients.setText("not-a-node-id") + page._save() + assert page.notice.text().startswith("Not saved") + assert service.settings.debug_enabled is False + assert service.settings.debug_clients == "" diff --git a/gui/tests/test_qt_screens.py b/gui/tests/test_qt_screens.py index 15b4bee..0afccef 100644 --- a/gui/tests/test_qt_screens.py +++ b/gui/tests/test_qt_screens.py @@ -12,7 +12,7 @@ from pathlib import Path import pytest -from PySide6.QtCore import Qt +from PySide6.QtCore import QEvent, Qt from PySide6.QtGui import QGuiApplication from PySide6.QtWidgets import QLabel @@ -32,7 +32,7 @@ from transferd_gui.ui.widgets import Banner, CopyField, TableWithEmpty EXPECTED_KEYS = [page_class.key for _, page_classes in NAVIGATION for page_class in page_classes] -EXPECTED_SECTIONS = ["OVERVIEW", "NETWORK", "TRANSFER", "TOOLS", "SYSTEM"] +EXPECTED_SECTIONS = ["OVERVIEW", "NETWORK", "TRANSFER", "TOOLS", "DEBUG", "SYSTEM"] def build_window(qapp, folder: Path, **changes): @@ -46,6 +46,14 @@ def build_window(qapp, folder: Path, **changes): return window, service +def dispose(qapp, win) -> None: + """Close a window and destroy it now. A theme change re-polishes every window that still exists, so windows left + alive make each later test slower than the one before it.""" + win.close() + win.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + + def pump(qapp, predicate, timeout: float = 20.0) -> bool: """Process Qt events (signals from the backend thread arrive this way) until `predicate` holds or time runs out.""" deadline = time.monotonic() + timeout @@ -67,8 +75,7 @@ def empty_snapshot(folder: Path): def window(qapp, tmp_path): win, _service = build_window(qapp, tmp_path) yield win - win.close() - win.deleteLater() + dispose(qapp, win) # ----- navigation and layout -------------------------------------------------------------------- @@ -98,13 +105,13 @@ def test_selecting_a_sidebar_entry_shows_that_screen(window): assert window.stack.currentWidget() is window.page(key) -def test_the_eleven_screens_have_titles_that_match_the_sidebar(window): +def test_every_screen_has_a_title_that_matches_the_sidebar(window): for row in range(window.nav.count()): item = window.nav.item(row) key = item.data(Qt.ItemDataRole.UserRole) if key is not None: assert item.text() == window.page(key).title - assert len(EXPECTED_KEYS) == 11 + assert len(EXPECTED_KEYS) == 13 # ----- empty state of every screen -------------------------------------------------------------- @@ -370,5 +377,5 @@ def test_every_screen_shows_real_data_once_a_peer_is_connected(qapp, tmp_path): assert settings_page.data_dir.text() == service.settings.data_dir assert len(settings_page.findChildren(Banner)) == 3 finally: - window.close() + dispose(qapp, window) peer.stop() diff --git a/gui/tests/test_wormhole_addresses.py b/gui/tests/test_wormhole_addresses.py new file mode 100644 index 0000000..548afc5 --- /dev/null +++ b/gui/tests/test_wormhole_addresses.py @@ -0,0 +1,116 @@ +"""The mailbox addresses in Settings: what is accepted, what is refused and why, the defaults, and the pins. Text only.""" + +from __future__ import annotations + +import pytest + +from transferd_gui.wormhole.addresses import ( + DEFAULT_PORT, + MAX_MAILBOXES, + MailboxAddress, + display_fingerprint, + normalise_fingerprint, + parse_address, + parse_list, +) + +PIN = "9f2c" * 16 # 64 hex characters + + +def test_a_wss_address_with_a_pin_is_read_with_its_pin_in_lower_case(): + address = parse_address(f"wss://Mailbox.Example.net:4470#{PIN.upper()}") + assert address == MailboxAddress("wss", "mailbox.example.net", 4470, PIN) + assert address.url == "wss://mailbox.example.net:4470" + assert address.text() == f"wss://mailbox.example.net:4470#{PIN}" + + +def test_the_port_defaults_to_4470_and_a_pin_is_optional(): + address = parse_address("wss://mailbox.example.net") + assert address.port == DEFAULT_PORT + assert address.pin == "" + assert address.text() == "wss://mailbox.example.net:4470" + + +def test_a_fingerprint_may_be_copied_with_spaces_colons_or_dashes(): + spaced = " ".join(PIN[i : i + 8] for i in range(0, 64, 8)) + colons = ":".join(PIN[i : i + 2] for i in range(0, 64, 2)) + assert normalise_fingerprint(spaced) == PIN + assert normalise_fingerprint(colons) == PIN + assert normalise_fingerprint(PIN.upper()) == PIN + + +def test_a_fingerprint_of_the_wrong_length_or_with_other_characters_is_refused(): + with pytest.raises(ValueError, match="64 hexadecimal"): + normalise_fingerprint("abcd") + with pytest.raises(ValueError, match="64 hexadecimal"): + normalise_fingerprint("zz" * 32) + + +def test_the_display_form_groups_a_fingerprint_in_eights(): + shown = display_fingerprint(PIN) + assert shown.split(" ") == [PIN[i : i + 8] for i in range(0, 64, 8)] + assert normalise_fingerprint(shown) == PIN + + +def test_plain_ws_is_accepted_for_this_computer_only(): + assert parse_address("ws://127.0.0.1:4470").loopback + assert parse_address("ws://localhost:4470").loopback + assert parse_address("ws://[::1]:4470").url == "ws://[::1]:4470" + with pytest.raises(ValueError, match="reaches only this computer"): + parse_address("ws://mailbox.example.net:4470") + with pytest.raises(ValueError, match="reaches only this computer"): + parse_address("ws://192.168.1.20:4470") + + +def test_a_fingerprint_on_a_ws_address_is_refused_because_ws_is_not_encrypted(): + with pytest.raises(ValueError, match="wss://"): + parse_address(f"ws://127.0.0.1:4470#{PIN}") + + +@pytest.mark.parametrize( + "text, problem", + [ + ("mailbox.example.net:4470", "must start with wss://"), + ("https://mailbox.example.net:4470", "must start with wss://"), + ("wss://mailbox.example.net:70000", "1 to 65535"), + ("wss://mailbox.example.net:port", "does not end in a port"), + ("wss://user:secret@mailbox.example.net:4470", "user name or password"), + ("wss://mailbox.example.net:4470/mailbox", "only a host and a port"), + ("wss://mailbox.example.net:4470?x=1", "only a host and a port"), + ("wss://mailbox.example.net:4470 extra", "spaces"), + ("", "empty"), + (" ", "empty"), + ], +) +def test_bad_addresses_are_refused_with_the_reason(text, problem): + with pytest.raises(ValueError, match=problem): + parse_address(text) + + +def test_an_empty_setting_is_no_list_at_all(): + assert parse_list("") == () + assert parse_list(" ") == () + + +def test_a_list_keeps_its_order_and_tolerates_spaces_around_the_commas(): + addresses = parse_list(f"wss://first.example.net:4470#{PIN}, wss://second.example.net:4470") + assert [a.host for a in addresses] == ["first.example.net", "second.example.net"] + assert addresses[0].pin == PIN + + +def test_a_list_with_an_empty_entry_is_refused(): + with pytest.raises(ValueError, match="entry 2 of the list is empty"): + parse_list("wss://a.example.net:4470,,wss://b.example.net:4470") + with pytest.raises(ValueError, match="entry 2 of the list is empty"): + parse_list("wss://a.example.net:4470,") + + +def test_a_list_longer_than_the_limit_is_refused(): + entries = ",".join(f"wss://m{i}.example.net:4470" for i in range(MAX_MAILBOXES + 1)) + with pytest.raises(ValueError, match="at most"): + parse_list(entries) + + +def test_the_same_mailbox_listed_twice_is_refused(): + with pytest.raises(ValueError, match="listed twice"): + parse_list("wss://a.example.net:4470,wss://A.example.net:4470") diff --git a/gui/tests/test_wormhole_codes.py b/gui/tests/test_wormhole_codes.py new file mode 100644 index 0000000..70faf26 --- /dev/null +++ b/gui/tests/test_wormhole_codes.py @@ -0,0 +1,108 @@ +"""Wormhole codes: spelling, reading back, and the checks that catch a mistyped or misordered code.""" + +from __future__ import annotations + +import pytest + +from transferd_gui.wormhole.codes import Code, generate, parse, word_for +from transferd_gui.wormhole.errors import CodeError +from transferd_gui.wormhole.wordlist import EVEN_WORDS, LOOKUP, ODD_WORDS + + +def test_a_generated_code_reads_back_to_the_same_nameplate_and_secret(): + code = generate(4217, lambda n: bytes([0x2A, 0x7F, 0xF0])) + again = parse(str(code)) + assert again == code + assert again.nameplate == 4217 + assert again.secret == bytes([0x2A, 0x7F, 0xF0]) + + +def test_the_words_alternate_between_the_even_and_odd_lists(): + code = Code(1, bytes([0, 0, 0])) + assert code.words == (EVEN_WORDS[0], ODD_WORDS[0], EVEN_WORDS[0]) + assert str(code) == f"1-{EVEN_WORDS[0]}-{ODD_WORDS[0]}-{EVEN_WORDS[0]}" + + +def test_the_password_includes_the_nameplate(): + code = Code(4217, bytes([0x2A, 0x7F, 0xF0])) + assert code.password() == str(code).encode("ascii") + assert code.password().startswith(b"4217-") + + +def test_reading_is_forgiving_about_case_spaces_and_underscores(): + code = Code(4217, bytes([0x2A, 0x7F, 0xF0])) + spelt = "-".join(code.words).upper() + assert parse(f" 4217 {spelt.replace('-', '_')} ") == code + assert parse(f"4217--{spelt.replace('-', ' ')}") == code + assert parse(f"0004217-{'-'.join(code.words)}") == code, "a nameplate with leading zeros reads the same" + + +def test_a_swapped_word_is_refused_with_its_position(): + code = Code(9, bytes([1, 2, 3])) + w = list(code.words) + w[1], w[2] = w[2], w[1] + with pytest.raises(CodeError, match="word 2 is in the wrong place"): + parse("9-" + "-".join(w)) + + +def test_a_missing_word_is_refused_before_anything_is_sent(): + code = Code(9, bytes([1, 2, 3])) + with pytest.raises(CodeError, match="a number and 3 words"): + parse(f"9-{code.words[0]}-{code.words[1]}") + + +def test_an_extra_word_is_refused_too(): + code = Code(9, bytes([1, 2, 3])) + with pytest.raises(CodeError, match="a number and 3 words"): + parse(f"9-{'-'.join(code.words)}-{EVEN_WORDS[4]}") + + +def test_an_unknown_word_is_named_in_the_refusal(): + with pytest.raises(CodeError, match="'zebrafish' is not a word"): + parse("9-zebrafish-aardvark-adroitness") + + +@pytest.mark.parametrize("nameplate", ["0", "65536", "99999999"]) +def test_a_nameplate_outside_the_range_is_refused(nameplate): + with pytest.raises(CodeError, match="must be from 1 to 65535"): + parse(f"{nameplate}-aardvark-absurd-accrue") + + +def test_a_nameplate_that_is_not_a_number_is_refused(): + with pytest.raises(CodeError, match="starts with a number"): + parse("abc-aardvark-absurd-accrue") + + +def test_a_code_that_is_not_text_is_refused(): + with pytest.raises(CodeError): + parse(None) # type: ignore[arg-type] + + +def test_a_byte_out_of_range_has_no_word(): + with pytest.raises(CodeError): + word_for(0, 256) + + +def test_the_word_lists_are_the_full_byte_range_and_do_not_repeat(): + assert len(EVEN_WORDS) == 256 and len(ODD_WORDS) == 256 + assert len(LOOKUP) == 512, "every word is distinct, so a word names exactly one byte and one position" + assert len(set(EVEN_WORDS) | set(ODD_WORDS)) == 512 + + +def test_generate_asks_for_three_random_bytes_and_uses_them_as_the_secret(): + asked = [] + + def fake(n): + asked.append(n) + return bytes([5, 6, 7]) + + code = generate(12, fake) + assert asked == [3] + assert code.secret == bytes([5, 6, 7]) + + +def test_a_code_with_a_bad_nameplate_or_secret_cannot_be_made(): + with pytest.raises(CodeError): + Code(0, bytes([1, 2, 3])) + with pytest.raises(CodeError): + Code(5, bytes([1, 2])) diff --git a/gui/tests/test_wormhole_e2e.py b/gui/tests/test_wormhole_e2e.py new file mode 100644 index 0000000..58b3430 --- /dev/null +++ b/gui/tests/test_wormhole_e2e.py @@ -0,0 +1,327 @@ +"""End to end, with faults in the middle: the real mailbox server, the real overlay sessions and, for the relay tests, the real +relay binary. + +- A route is cut while a file is moving over two routes. The overlay carries what was in flight on the cut route over the + other one, and the file arrives intact. +- The sender's mailbox connection is cut before the other side has arrived. The sender reconnects, and the transfer still + completes. +- A file moves through the relay, with no direct address offered at all. Needs TRANSFERD_RELAYD (see gui/README.md). +- A larger file through the relay: a known stall, recorded as an expected failure with the reproduction (see WORMHOLE.md). + +Faults are injected with a TCP forwarder that counts the bytes it passes and can drop every connection through it. Nothing +in the library is patched. +""" + +from __future__ import annotations + +import asyncio +import os +import socket +import subprocess +from contextlib import contextmanager +from dataclasses import replace +from pathlib import Path +from typing import List, Optional, Tuple + +import pytest + +from test_wormhole_mailbox import run +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.endpoint import OverlayTransit +from transferd_gui.wormhole.session import Receiver, Sender +from transferd_gui.wormhole.transfer import prepare_file + +MIB = 1024 * 1024 +RELAYD = os.environ.get("TRANSFERD_RELAYD", "") +needs_relayd = pytest.mark.skipif( + not RELAYD or not Path(RELAYD).exists(), + reason="set TRANSFERD_RELAYD to the built relayd binary", +) + + +class CutProxy: + """A TCP forwarder in front of a listener. It counts the bytes it passes and can drop every connection through it.""" + + def __init__(self) -> None: + self.port = 0 + self.forwarded = 0 + self.accepted = 0 + self._target = 0 + self._server: Optional[asyncio.AbstractServer] = None + self._pairs: List[Tuple[asyncio.StreamWriter, asyncio.StreamWriter]] = [] + + async def start(self, target_port: int) -> None: + self._target = target_port + self._server = await asyncio.start_server(self._accept, "127.0.0.1", 0) + self.port = int(self._server.sockets[0].getsockname()[1]) + + async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + self.accepted += 1 + try: + up_reader, up_writer = await asyncio.open_connection("127.0.0.1", self._target) + except OSError: + writer.close() + return + self._pairs.append((writer, up_writer)) + await asyncio.gather(self._pipe(reader, up_writer), self._pipe(up_reader, writer)) + + async def _pipe(self, source: asyncio.StreamReader, sink: asyncio.StreamWriter) -> None: + try: + while True: + data = await source.read(65536) + if not data: + break + self.forwarded += len(data) + sink.write(data) + await sink.drain() + except (ConnectionError, OSError): + pass + finally: + sink.close() + + def cut(self, stop_accepting: bool = True) -> None: + """Drop every connection through the proxy now. With `stop_accepting`, it also stops listening, so a route that + was cut cannot come back through it.""" + if stop_accepting and self._server is not None: + self._server.close() + for client, upstream in self._pairs: + client.transport.abort() + upstream.transport.abort() + self._pairs = [] + + def close(self) -> None: + self.cut(stop_accepting=True) + + +class FrontedReceiver(OverlayTransit): + """A receiver whose only offered addresses are proxies in front of its listener. Every route the sender can use runs + through a proxy the test can cut; the receiver's own listener stays open behind them.""" + + def __init__(self, fronts: int, **kwargs) -> None: + super().__init__(advertise=["127.0.0.1"], listen_host="127.0.0.1", **kwargs) + self.fronts = [CutProxy() for _ in range(fronts)] + + async def open(self) -> None: + first = self._server is None + await super().open() + if first: + for front in self.fronts: + await front.start(self._port) + + def local_identity(self) -> P.PeerIdentity: + base = super().local_identity() + if not self.fronts or any(front.port == 0 for front in self.fronts): + return base + return replace(base, hints=tuple(P.Hint("127.0.0.1", front.port) for front in self.fronts)) + + +def loopback(**kwargs) -> OverlayTransit: + return OverlayTransit(advertise=["127.0.0.1"], listen_host="127.0.0.1", **kwargs) + + +def payload(size: int) -> bytes: + return bytes((i * 131 + (i >> 9)) & 0xFF for i in range(size)) + + +def port_of(url: str) -> int: + return int(url.rsplit(":", 1)[1]) + + +async def settle(*tasks: asyncio.Future) -> None: + """Stop tasks that may still be running, and collect their results, so a failure in one side is never left unretrieved.""" + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +async def cut_first_when_both_carry( + fronts: List[CutProxy], sent_task: asyncio.Future, minimum: int, transit: OverlayTransit +) -> Tuple[List[int], list]: + """Wait until every route has carried `minimum` bytes, then cut the first one. Returns what each carried before the cut, + and the sender's route counters as they were while the transfer still ran (the session is gone once it has ended).""" + while min(front.forwarded for front in fronts) < minimum: + if sent_task.done(): + raise AssertionError("the transfer finished before every route had carried data") + await asyncio.sleep(0.005) + before = [front.forwarded for front in fronts] + fronts[0].cut() + latest: list = [] + while not sent_task.done(): + reports = transit.route_reports() + if reports: + latest = reports + if any(report.retx_bytes for report in latest): + break + await asyncio.sleep(0.005) + return before, latest + + +# ----- faults in the middle --------------------------------------------------------------------------- + + +def test_a_route_cut_mid_transfer_is_carried_on_the_other_route(tmp_path): + data = payload(32 * MIB + 77) + source = tmp_path / "large.bin" + source.write_bytes(data) + folder = tmp_path / "downloads" + minimum = 256 * 1024 + + def scenario(server, url): + async def go(): + offer, path = prepare_file(source) + sender_transit = loopback(name="sender", streams=4) + receiver_transit = FrontedReceiver(2, name="receiver", streams=4) + sender = Sender(url, transit=sender_transit, offer=offer, source=path, answer_timeout=60) + code = await sender.start() + sent_task = asyncio.ensure_future(sender.run()) + receiver = Receiver(url, code, transit=receiver_transit) + try: + await receiver.connect() + await receiver.offer() + await receiver.answer(True) + finish = asyncio.ensure_future(receiver.finish(folder)) + cutter = asyncio.ensure_future( + cut_first_when_both_carry(receiver_transit.fronts, sent_task, minimum, sender_transit) + ) + received = await finish + sent = await sent_task + before, reports = await cutter + after = [front.forwarded for front in receiver_transit.fronts] + return sent, received, before, after, reports + finally: + for front in receiver_transit.fronts: + front.close() + await settle(sent_task) + + return go() + + sent, received, before, after, reports = run(scenario, timeout=180) + assert sent.ok + assert received.path.read_bytes() == data + assert all(count >= minimum for count in before), "both routes must have carried data before the cut" + assert after[1] > before[1], "the route that was not cut kept carrying the rest of the file" + assert reports, "the sender still had its session when the transfer ended" + assert sum(report.retx_bytes for report in reports) > 0, "frames in flight on the cut route were sent again on another route" + + +def test_the_mailbox_connection_cut_before_the_other_side_arrives_is_reconnected(tmp_path): + data = payload(3 * MIB + 5) + source = tmp_path / "after-reconnect.bin" + source.write_bytes(data) + folder = tmp_path / "downloads" + + def scenario(server, url): + async def go(): + front = CutProxy() + await front.start(port_of(url)) + sent_task: Optional[asyncio.Future] = None + try: + offer, path = prepare_file(source) + sender = Sender( + f"ws://127.0.0.1:{front.port}", + transit=loopback(name="sender"), + offer=offer, + source=path, + answer_timeout=60, + ) + code = await sender.start() + # Drop the sender's mailbox connection before the other side has even claimed the code. The proxy keeps + # listening, so the sender has to reconnect through it. + front.cut(stop_accepting=False) + sent_task = asyncio.ensure_future(sender.run()) + receiver = Receiver(url, code, transit=loopback(name="receiver")) + await receiver.connect() + await receiver.offer() + await receiver.answer(True) + received = await receiver.finish(folder) + sent = await sent_task + return sent, received, front.accepted + finally: + front.close() + if sent_task is not None: + await settle(sent_task) + + return go() + + sent, received, accepted = run(scenario, timeout=120) + assert sent.ok + assert received.path.read_bytes() == data + assert accepted >= 2, "the sender reconnected to the mailbox through the proxy" + + +# ----- the relay -------------------------------------------------------------------------------------- + + +def _free_udp_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +@contextmanager +def relay_process(): + port = _free_udp_port() + env = {**os.environ, "RELAYD_BIND": f"127.0.0.1:{port}", "RELAYD_DIFFICULTY": "12"} + proc = subprocess.Popen([RELAYD], env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + line = proc.stdout.readline() + assert "listening" in line, proc.stderr.read() + yield f"127.0.0.1:{port}" + finally: + proc.kill() + + +def relay_transfer(tmp_path: Path, data: bytes, timeout: float): + """Move `data` with the receiver offering no direct address, so the relay is the only route. Returns what the sender + and the receiver each got back.""" + source = tmp_path / "via-relay.bin" + source.write_bytes(data) + folder = tmp_path / "downloads" + with relay_process() as relay_addr: + + def scenario(server, url): + async def go(): + offer, path = prepare_file(source) + sender_transit = OverlayTransit(name="sender", relay=relay_addr, streams=2) + receiver_transit = OverlayTransit(name="receiver", relay=relay_addr, advertise=[], streams=2) + sender = Sender(url, transit=sender_transit, offer=offer, source=path, answer_timeout=60) + code = await sender.start() + sent_task = asyncio.ensure_future(sender.run()) + receiver = Receiver(url, code, transit=receiver_transit) + try: + await receiver.connect() + assert receiver_transit.local_identity().hints == (), "the receiver offers no direct address" + await receiver.offer() + await receiver.answer(True) + received = await receiver.finish(folder) + sent = await sent_task + return sent, received + finally: + await settle(sent_task) + + return go() + + return run(scenario, timeout=timeout) + + +@needs_relayd +def test_a_file_moves_through_the_relay_when_no_direct_address_is_offered(tmp_path): + data = payload(MIB) + sent, received = relay_transfer(tmp_path, data, timeout=120) + assert sent.ok + # The receiver offers no direct address, so the relay was the only route the sender could use: the file arriving + # proves the relay carried it. + assert received.path.read_bytes() == data + + +@needs_relayd +@pytest.mark.xfail( + strict=True, + reason="known stall: over the relay, a transfer above about 1 MiB stops with the route at total loss. " + "Reproduction and timings: gui/docs/WORMHOLE.md, section Known limits.", +) +def test_a_file_of_two_mib_moves_through_the_relay(tmp_path): + data = payload(2 * MIB + 9) + sent, received = relay_transfer(tmp_path, data, timeout=60) + assert sent.ok + assert received.path.read_bytes() == data diff --git a/gui/tests/test_wormhole_endpoint.py b/gui/tests/test_wormhole_endpoint.py new file mode 100644 index 0000000..d5e205c --- /dev/null +++ b/gui/tests/test_wormhole_endpoint.py @@ -0,0 +1,193 @@ +"""The overlay transit on 127.0.0.1: a wormhole file moves over a real overlay session with the real hybrid handshake, and the +identity checks refuse a stranger. The mailbox is the real server. The relay path is tested in the end-to-end file.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from test_wormhole_mailbox import run +from transferd_gui.wormhole import endpoint +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.endpoint import OverlayTransit +from transferd_gui.wormhole.errors import TransferError +from transferd_gui.wormhole.session import Receiver, Sender +from transferd_gui.wormhole.transfer import prepare_file + + +def loopback(**kwargs) -> OverlayTransit: + return OverlayTransit(advertise=["127.0.0.1"], listen_host="127.0.0.1", **kwargs) + + +async def move(url: str, source: Path, folder: Path, sender_transit: OverlayTransit, receiver_transit: OverlayTransit): + offer, path = prepare_file(source) + sender = Sender(url, transit=sender_transit, offer=offer, source=path, answer_timeout=30) + code = await sender.start() + send_task = asyncio.ensure_future(sender.run()) + receiver = Receiver(url, code, transit=receiver_transit) + await receiver.connect() + await receiver.offer() + await receiver.answer(True) + received = await receiver.finish(folder) + sent = await send_task + return sent, received + + +def payload(size: int) -> bytes: + return bytes((i * 37 + (i >> 8)) & 0xFF for i in range(size)) + + +def test_a_file_moves_over_a_direct_overlay_route(tmp_path): + data = payload(3 * 1024 * 1024 + 123) + source = tmp_path / "movie.bin" + source.write_bytes(data) + folder = tmp_path / "downloads" + + def scenario(server, url): + async def go(): + return await move(url, source, folder, loopback(name="sender"), loopback(name="receiver")) + + return go() + + sent, received = run(scenario, timeout=60) + assert sent.ok + assert received.kind == "file" + assert received.path.read_bytes() == data + assert [p.name for p in folder.iterdir()] == ["movie.bin"], "only the finished file is left in the download folder" + + +def test_a_file_larger_than_the_window_is_paced_by_progress_and_still_arrives(tmp_path, monkeypatch): + monkeypatch.setattr(endpoint, "WINDOW_BYTES", 256 * 1024) + monkeypatch.setattr(endpoint, "PROGRESS_BYTES", 128 * 1024) + data = payload(3 * 1024 * 1024) + source = tmp_path / "paced.bin" + source.write_bytes(data) + folder = tmp_path / "downloads" + + def scenario(server, url): + async def go(): + return await move(url, source, folder, loopback(name="sender", streams=4), loopback(name="receiver")) + + return go() + + sent, received = run(scenario, timeout=90) + assert sent.ok + assert received.path.read_bytes() == data + + +def test_an_empty_file_moves(tmp_path): + source = tmp_path / "empty.txt" + source.write_bytes(b"") + folder = tmp_path / "downloads" + + def scenario(server, url): + async def go(): + return await move(url, source, folder, loopback(name="sender"), loopback(name="receiver")) + + return go() + + sent, received = run(scenario, timeout=60) + assert sent.ok + assert received.path.read_bytes() == b"" + + +def test_dialling_collects_every_route_that_comes_up_and_skips_a_dead_one(tmp_path): + """Two addresses are offered; one has nothing listening. The dial keeps the route that works.""" + + async def scenario(): + receiver = loopback(name="receiver") + await receiver.open() + try: + live = receiver.local_identity() + dead_port = 1 # nothing listens on port 1 + peer = P.PeerIdentity( + live.node_id, + live.public_key, + "receiver", + "", + (P.Hint("127.0.0.1", dead_port), P.Hint("127.0.0.1", live.hints[0].port)), + ) + sender = loopback(name="sender") + links = await sender._dial(peer) + try: + assert len(links) == 1 + finally: + for link in links: + link.close() + await sender.close() + finally: + await receiver.close() + + asyncio.run(asyncio.wait_for(scenario(), 30)) + + +def test_a_connection_from_anyone_but_the_expected_peer_is_not_admitted(): + """The receiver expects someone else. The sender does check the receiver's key, and the handshake with the real + receiver completes on its side; the receiver then closes the connection and admits nothing.""" + + async def scenario(): + receiver = loopback(name="receiver") + await receiver.open() + try: + live = receiver.local_identity() + stranger = P.PeerIdentity("cd" * 32, b"\x02" * 2624, "someone", "", ()) + receiver.expect_peer(stranger) + peer = P.PeerIdentity(live.node_id, live.public_key, "receiver", "", live.hints) + sender = loopback(name="sender") + links = [] + try: + links = await sender._dial(peer) + except TransferError: + pass # the close may land before the sender reads the answer; either way nothing is admitted + await asyncio.sleep(0.3) + assert receiver._inbound.empty(), "the receiver admits no connection from anyone but the expected peer" + for link in links: + link.close() + await sender.close() + finally: + await receiver.close() + + asyncio.run(asyncio.wait_for(scenario(), 30)) + + +def test_a_direct_address_must_be_the_one_the_code_named(): + """The address answers, but with a different identity from the one the code named: the link is not made.""" + + async def scenario(): + receiver = loopback(name="receiver") + await receiver.open() + try: + live = receiver.local_identity() + receiver.expect_peer(P.PeerIdentity(live.node_id, live.public_key, "receiver", "", ())) + wrong_node = P.PeerIdentity("ef" * 32, live.public_key, "receiver", "", live.hints) + sender = loopback(name="sender") + with pytest.raises(TransferError): + await sender._dial(wrong_node) + await sender.close() + finally: + await receiver.close() + + asyncio.run(asyncio.wait_for(scenario(), 30)) + + +def test_the_local_identity_lists_the_listening_port_for_each_advertised_address(): + async def scenario(): + transit = loopback(name="x") + assert transit.local_identity().hints == (), "nothing is listening yet, so no place to reach" + await transit.open() + try: + identity = transit.local_identity() + assert identity.hints == (P.Hint("127.0.0.1", identity.hints[0].port),) + assert identity.hints[0].port > 0 + finally: + await transit.close() + + asyncio.run(asyncio.wait_for(scenario(), 15)) + + +def test_a_relay_address_must_be_host_and_port(): + with pytest.raises(TransferError, match="host:port"): + endpoint._parse_addr("no-port-here") + assert endpoint._parse_addr("relay.example:7777") == ("relay.example", 7777) diff --git a/gui/tests/test_wormhole_host.py b/gui/tests/test_wormhole_host.py new file mode 100644 index 0000000..d48af1c --- /dev/null +++ b/gui/tests/test_wormhole_host.py @@ -0,0 +1,258 @@ +"""The mailbox list and the hosted mailbox: the settings that hold them, the hosted mailbox's start, stop and status, what it +serves on this computer and on the network, and a wormhole on this computer that meets on its own mailbox when no list is set. + +Hosting binds to 127.0.0.1 in these tests. The app binds to all interfaces when the network setting is on; the test injects the +address so that nothing listens beyond this computer.""" + +from __future__ import annotations + +import asyncio +import socket +from pathlib import Path + +import pytest + +from support import free_port, make_settings +from transferd_gui.backend.mailbox_host import MailboxHost +from transferd_gui.backend.wormhole import NO_MAILBOX, WormholeService +from transferd_gui.model.settings import SettingsError, validate +from transferd_gui.wormhole.errors import WormholeError +from transferd_gui.wormhole.keys import new_side +from transferd_gui.wormhole.mailbox import MailboxClient + +PIN = "9f2c" * 16 + + +def base(tmp_path: Path, **changes) -> dict: + data = tmp_path / "data" + return {"data_dir": str(data), "download_dir": str(data / "received"), **changes} + + +class FakeService: + """The part of the app service that the wormhole service reads.""" + + def __init__(self, settings, host: MailboxHost) -> None: + self.settings = settings + self.mailbox_host = host + + +async def settle(*tasks) -> None: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +# ----- settings -------------------------------------------------------------------------------------- + + +def test_the_hosting_defaults_are_off_and_the_standard_port(tmp_path): + settings = validate(base(tmp_path)) + assert settings.wormhole_host is False + assert settings.wormhole_host_network is False + assert settings.wormhole_host_port == 4470 + assert settings.wormhole_mailbox == "" + + +def test_a_list_of_mailboxes_with_pins_is_accepted(tmp_path): + settings = validate(base(tmp_path, wormhole_mailbox=f"wss://a.example.net:4470#{PIN}, ws://127.0.0.1:4470")) + assert settings.wormhole_mailbox.startswith("wss://a.example.net") + + +@pytest.mark.parametrize( + "changes, problem", + [ + ({"wormhole_mailbox": "ws://a.example.net:4470"}, "reaches only this computer"), + ({"wormhole_mailbox": "wss://a.example.net:4470,,wss://b.example.net:4470"}, "entry 2"), + ({"wormhole_mailbox": f"wss://a.example.net:4470#{'zz' * 32}"}, "64 hexadecimal"), + ({"wormhole_mailbox": "wss://a.example.net:4470 " + "x" * 10}, "spaces"), + ({"wormhole_mailbox": "x" * 700}, "longer than 600"), + ({"wormhole_host_port": 0}, "wormhole_host_port must be between 1 and 65535"), + ({"wormhole_host": "yes"}, "wormhole_host must be on or off"), + ({"wormhole_host_network": 1}, "wormhole_host_network must be on or off"), + ], +) +def test_bad_mailbox_and_hosting_settings_are_named_and_refused(tmp_path, changes, problem): + with pytest.raises(SettingsError) as refused: + validate(base(tmp_path, **changes)) + assert any(problem in message for message in refused.value.problems) + + +def test_a_wormhole_with_no_list_and_no_hosting_is_told_to_set_one(tmp_path): + settings = make_settings(tmp_path) + service = WormholeService(FakeService(settings, MailboxHost(tmp_path / "wormhole"))) + assert service.mailbox() == "" + assert service.problem() == NO_MAILBOX + with pytest.raises(WormholeError, match="host one on this computer"): + asyncio.run(service.start_send("text", "hello")) + + +def test_a_listed_mailbox_is_used_in_preference_to_the_hosted_one(tmp_path): + settings = make_settings(tmp_path, wormhole_mailbox="ws://127.0.0.1:9999") + service = WormholeService(FakeService(settings, MailboxHost(tmp_path / "wormhole"))) + assert service.mailbox() == "ws://127.0.0.1:9999" + assert service.problem() == "" + + +# ----- the hosted mailbox ---------------------------------------------------------------------------- + + +def test_hosting_off_reports_nothing_and_offers_no_address(tmp_path): + async def main(): + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=False)) + status = host.status() + assert not status.enabled and not status.running + assert host.address_here() == "" + assert host.share_line() == "" + + asyncio.run(main()) + + +def test_hosting_on_this_computer_listens_on_loopback_without_tls(tmp_path): + port = free_port() + + async def main(): + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port)) + status = host.status() + assert status.running and status.port == port and not status.network and status.fingerprint == "" + assert host.address_here() == f"ws://127.0.0.1:{port}" + assert host.share_line() == "", "a mailbox on this computer only has no share line" + c = MailboxClient(host.address_here(), new_side(), timeout=3) + await c.connect() + assert await c.allocate() > 0 + await c.disconnect() + await host.stop() + assert not host.status().running + + asyncio.run(main()) + + +def test_hosting_on_the_network_serves_wss_pinned_to_its_own_certificate(tmp_path): + port = free_port() + + async def main(): + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port, wormhole_host_network=True)) + status = host.status() + assert status.running and status.network + assert len(status.fingerprint) == 64 + assert host.address_here() == f"wss://127.0.0.1:{port}#{status.fingerprint}" + assert status.share_line("192.168.1.20") == f"wss://192.168.1.20:{port}#{status.fingerprint}" + assert status.share_line("") == "" + c = MailboxClient(host.address_here(), new_side(), timeout=3, attempts=1) + await c.connect() + assert await c.allocate() > 0 + await c.disconnect() + await host.stop() + + asyncio.run(main()) + + +def test_the_identity_of_a_network_mailbox_is_kept_across_restarts(tmp_path): + port = free_port() + + async def main(): + settings = make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port, wormhole_host_network=True) + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(settings) + first = host.status().fingerprint + await host.stop() + await host.apply(settings) + assert host.status().fingerprint == first, "the other computers' pins stay valid across a restart" + await host.stop() + + asyncio.run(main()) + + +def test_a_port_already_in_use_is_reported_and_nothing_is_raised(tmp_path): + port = free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen() + try: + + async def main(): + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port)) + status = host.status() + assert not status.running + assert f"could not listen on port {port}" in status.error + + asyncio.run(main()) + finally: + blocker.close() + + +def test_a_certificate_that_cannot_be_written_is_reported(tmp_path): + folder_is_a_file = tmp_path / "not-a-folder" + folder_is_a_file.write_text("in the way") + + async def main(): + host = MailboxHost(folder_is_a_file, network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=free_port(), wormhole_host_network=True)) + status = host.status() + assert not status.running + assert "could not make the mailbox's certificate" in status.error + + asyncio.run(main()) + + +def test_applying_the_same_settings_again_keeps_the_running_server(tmp_path): + port = free_port() + + async def main(): + settings = make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port) + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(settings) + first = host._server + await host.apply(settings) + assert host._server is first + await host.stop() + + asyncio.run(main()) + + +def test_changing_the_port_moves_the_mailbox_and_turning_it_off_stops_it(tmp_path): + first_port, second_port = free_port(), free_port() + + async def main(): + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=first_port)) + assert host.status().port == first_port + await host.apply(make_settings(tmp_path, wormhole_host=True, wormhole_host_port=second_port)) + assert host.status().port == second_port + await host.apply(make_settings(tmp_path, wormhole_host=False, wormhole_host_port=second_port)) + assert not host.status().running and host.address_here() == "" + with pytest.raises(OSError): + socket.create_connection(("127.0.0.1", second_port), timeout=0.5) # nothing listens any more + + asyncio.run(main()) + + +# ----- a wormhole on this computer, on its own mailbox ---------------------------------------------- + + +def test_a_wormhole_with_no_list_meets_on_this_computers_own_mailbox(tmp_path): + port = free_port() + + async def main(): + settings = make_settings(tmp_path, wormhole_host=True, wormhole_host_port=port) + host = MailboxHost(tmp_path / "wormhole", network_bind="127.0.0.1") + await host.apply(settings) + service = WormholeService(FakeService(settings, host)) + assert service.mailbox() == f"ws://127.0.0.1:{port}" + assert service.problem() == "" + sender = await service.start_send("text", "meeting on the hosted mailbox") + sent = asyncio.ensure_future(service.run_send(sender)) + try: + receiver = await service.open_receive(str(sender.code)) + received = await service.finish_receive(receiver, True) + assert received.kind == "text" + assert received.text == "meeting on the hosted mailbox" + assert (await sent).ok + finally: + await settle(sent) + await host.stop() + + asyncio.run(main()) diff --git a/gui/tests/test_wormhole_keys.py b/gui/tests/test_wormhole_keys.py new file mode 100644 index 0000000..0a1a22f --- /dev/null +++ b/gui/tests/test_wormhole_keys.py @@ -0,0 +1,135 @@ +"""The wormhole's keys: the SPAKE2 exchange agrees only when the codes match, and each sealed message opens only where it was sealed.""" + +from __future__ import annotations + +import pytest + +from transferd_gui.wormhole.codes import Code +from transferd_gui.wormhole.errors import OpenError, PakeError +from transferd_gui.wormhole.keys import Keys, Pake, new_message_id, new_side, open_sealed, seal + + +def exchange(code_a: Code, code_b: Code) -> tuple[Keys, Keys]: + """Two sides run the key exchange in memory, each with its own code.""" + a = Pake(code_a.password()) + b = Pake(code_b.password()) + return a.finish(b.outbound), b.finish(a.outbound) + + +CODE = Code(4217, bytes([0x2A, 0x7F, 0xF0])) + + +def test_the_same_code_gives_both_sides_the_same_keys(): + keys_a, keys_b = exchange(CODE, CODE) + side = new_side() + assert keys_a.phase_key(side, "version") == keys_b.phase_key(side, "version") + assert keys_a.phase_key(side, "identity") != keys_a.phase_key(side, "version"), "a key is per phase" + + +def test_a_different_code_gives_different_keys_and_nothing_opens(): + keys_a, keys_b = exchange(CODE, Code(4217, bytes([0x2A, 0x7F, 0xF1]))) + side_a = new_side() + sealed = seal(keys_a, side_a, "version", new_message_id(), b'{"protocol": 1}') + with pytest.raises(OpenError, match="the code is wrong"): + open_sealed(keys_b, side_a, "version", "0000", sealed) + + +def test_a_different_nameplate_is_a_different_password(): + keys_a, keys_b = exchange(CODE, Code(4218, CODE.secret)) + side = new_side() + sealed = seal(keys_a, side, "version", new_message_id(), b"x") + with pytest.raises(OpenError): + open_sealed(keys_b, side, "version", "0000", sealed) + + +def test_a_sealed_message_opens_for_the_side_that_sent_it(): + keys_a, keys_b = exchange(CODE, CODE) + side_a = new_side() + message_id = new_message_id() + sealed = seal(keys_a, side_a, "identity", message_id, b'{"node_id": "x"}') + assert open_sealed(keys_b, side_a, "identity", message_id, sealed) == b'{"node_id": "x"}' + + +def test_a_message_reflected_back_to_its_sender_does_not_open_as_the_other_side(): + keys_a, _keys_b = exchange(CODE, CODE) + side_a, side_b = new_side(), new_side() + sealed = seal(keys_a, side_a, "offer", new_message_id(), b"offer") + with pytest.raises(OpenError): + open_sealed(keys_a, side_b, "offer", "0000", sealed) + + +def test_a_message_in_another_phase_does_not_open(): + keys_a, keys_b = exchange(CODE, CODE) + side = new_side() + message_id = new_message_id() + sealed = seal(keys_a, side, "offer", message_id, b"offer") + with pytest.raises(OpenError): + open_sealed(keys_b, side, "answer", message_id, sealed) + + +def test_a_message_under_another_id_does_not_open(): + keys_a, keys_b = exchange(CODE, CODE) + side = new_side() + sealed = seal(keys_a, side, "offer", "a1b2", b"offer") + with pytest.raises(OpenError): + open_sealed(keys_b, side, "offer", "a1b3", sealed) + + +def test_a_changed_byte_does_not_open(): + keys_a, keys_b = exchange(CODE, CODE) + side = new_side() + sealed = bytearray(seal(keys_a, side, "offer", "a1b2", b"offer text")) + sealed[-1] ^= 0x01 + with pytest.raises(OpenError): + open_sealed(keys_b, side, "offer", "a1b2", bytes(sealed)) + + +def test_a_message_too_short_to_hold_its_nonce_and_tag_does_not_open(): + keys_a, _ = exchange(CODE, CODE) + with pytest.raises(OpenError, match="too short"): + open_sealed(keys_a, new_side(), "offer", "a1b2", b"short") + + +def test_each_seal_uses_a_fresh_nonce(): + keys_a, _ = exchange(CODE, CODE) + side = new_side() + first = seal(keys_a, side, "offer", "a1b2", b"same") + second = seal(keys_a, side, "offer", "a1b2", b"same") + assert first[:12] != second[:12] + assert first != second + + +def test_a_malformed_key_exchange_message_is_refused(): + with pytest.raises(PakeError): + Pake(CODE.password()).finish(b"\x00" * 33) + with pytest.raises(PakeError): + Pake(CODE.password()).finish(b"short") + with pytest.raises(PakeError, match="empty"): + Pake(CODE.password()).finish(b"") + + +def test_a_key_exchange_is_used_once_and_a_second_finish_says_so(): + pake = Pake(CODE.password()) + pake.finish(Pake(CODE.password()).outbound) + with pytest.raises(PakeError, match="already finished"): + pake.finish(Pake(CODE.password()).outbound) + + +def test_a_side_id_must_be_sixteen_lower_case_hex_characters(): + keys_a, _ = exchange(CODE, CODE) + with pytest.raises(PakeError): + keys_a.phase_key("ABCDEF0123456789", "offer") + with pytest.raises(PakeError): + keys_a.phase_key("short", "offer") + + +def test_the_root_key_must_be_thirty_two_bytes(): + with pytest.raises(PakeError): + Keys(b"short") + + +def test_side_and_message_ids_are_random_and_well_formed(): + side = new_side() + assert len(side) == 16 and all(c in "0123456789abcdef" for c in side) + assert len(new_message_id()) == 4 + assert new_side() != new_side() diff --git a/gui/tests/test_wormhole_limits.py b/gui/tests/test_wormhole_limits.py new file mode 100644 index 0000000..33ba867 --- /dev/null +++ b/gui/tests/test_wormhole_limits.py @@ -0,0 +1,197 @@ +"""The mailbox's limits and refusals, against the real server on 127.0.0.1: every refusal has a code, requests are rate-limited per +address and say when to retry, connections and nameplates are capped, and a connection that never binds is closed. Each test +runs its own server, the same as `test_wormhole_mailbox.py`.""" + +from __future__ import annotations + +import asyncio +import json + +import pytest +from websockets.asyncio.client import connect +from websockets.exceptions import ConnectionClosed + +from transferd_gui.wormhole.errors import MailboxError +from transferd_gui.wormhole.keys import new_side +from transferd_gui.wormhole.mailbox import MailboxClient +from transferd_gui.wormhole.server import APP_ID, PROTOCOL +from test_wormhole_mailbox import client, next_of, raw_session, run + + +def test_every_refusal_carries_a_machine_readable_code(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "allocate"})) + assert (await next_of(ws, "error"))["code"] == "not_bound" + await ws.send(json.dumps({"type": "bind", "appid": "someone-else/9", "side": new_side()})) + assert (await next_of(ws, "error"))["code"] == "wrong_app" + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": "not-a-side"})) + assert (await next_of(ws, "error"))["code"] == "bad_side" + side = new_side() + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": side})) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": side})) + assert (await next_of(ws, "error"))["code"] == "already_bound" + await ws.send(json.dumps({"type": "frobnicate"})) + assert (await next_of(ws, "error"))["code"] == "unknown_message" + await ws.send("not json at all") + assert (await next_of(ws, "error"))["code"] == "bad_request" + await ws.send(json.dumps({"type": "claim", "nameplate": "x"})) + assert (await next_of(ws, "error"))["code"] == "bad_nameplate" + await ws.send(json.dumps({"type": "open", "mailbox": "nope"})) + assert (await next_of(ws, "error"))["code"] == "no_mailbox" + await ws.send(json.dumps({"type": "allocate"})) + nameplate = json.loads(await ws.recv())["nameplate"] + await ws.send(json.dumps({"type": "claim", "nameplate": nameplate})) + mailbox = (await next_of(ws, "claimed"))["mailbox"] + await ws.send(json.dumps({"type": "add", "mailbox": mailbox, "id": "zz", "phase": "pake", "body": "00"})) + assert (await next_of(ws, "error"))["code"] == "bad_id" + await ws.send(json.dumps({"type": "add", "mailbox": mailbox, "id": "beef", "phase": "PAKE", "body": "00"})) + assert (await next_of(ws, "error"))["code"] == "bad_phase" + await ws.send(json.dumps({"type": "add", "mailbox": mailbox, "id": "beef", "phase": "pake", "body": "zz"})) + assert (await next_of(ws, "error"))["code"] == "bad_body" + await ws.send(json.dumps({"type": "add", "mailbox": mailbox, "id": "beef", "phase": "pake", "body": "ab" * 65537})) + error = await next_of(ws, "error") + assert error["code"] == "too_big" and error["id"] == "beef" + await ws.close() + + run(scenario) + + +def test_the_welcome_names_the_protocol_and_the_limits(): + async def scenario(server, url): + ws, welcome = await raw_session(url) + assert welcome["protocol"] == PROTOCOL + assert welcome["limits"]["bind_timeout_s"] > 0 + assert welcome["limits"]["max_message_bytes"] == 65536 + await ws.close() + + run(scenario) + + +def test_allocation_past_the_address_rate_is_refused_with_the_time_to_wait(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": new_side()})) + await ws.send(json.dumps({"type": "allocate"})) + assert (await next_of(ws, "allocated"))["nameplate"].isdigit() + await ws.send(json.dumps({"type": "allocate"})) + refused = await next_of(ws, "error") + assert refused["code"] == "rate_limited" + assert refused["orig"] == "allocate" + assert 0 < refused["retry_after"] <= 1.0 + await asyncio.sleep(refused["retry_after"] + 0.05) + await ws.send(json.dumps({"type": "allocate"})) + assert (await next_of(ws, "allocated"))["nameplate"].isdigit() + await ws.close() + + run(scenario, rates={"allocate": (1.0, 20.0)}) + + +def test_a_client_waits_out_a_rate_limit_and_carries_on(): + async def scenario(server, url): + c = await client(url) + first = await c.allocate() + second = await c.allocate() # refused once, then sent after the time the mailbox gave + assert first != second + await c.disconnect() + + run(scenario, rates={"allocate": (1.0, 20.0)}) + + +def test_an_add_past_its_rate_is_sent_again_and_is_not_lost(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("pake", b"one") + await a.add("version", b"two") # the second add is refused once, then sent again when allowed + assert (await b.receive(2)).body == b"one" + assert (await b.receive(2)).body == b"two" + await a.disconnect() + await b.disconnect() + + run(scenario, rates={"add": (1.0, 20.0)}) + + +def test_a_connection_beyond_the_address_limit_is_refused_as_busy(): + async def scenario(server, url): + held = [await connect(url) for _ in range(2)] + for ws in held: + await ws.recv() # the welcome + third = await connect(url) + refusal = json.loads(await third.recv()) + assert refusal["type"] == "error" and refusal["code"] == "busy" + assert refusal["retry_after"] > 0 + with pytest.raises(ConnectionClosed): + await third.recv() + for ws in held: + await ws.close() + + run(scenario, max_connections_per_address=2) + + +def test_a_client_refused_as_busy_says_so_rather_than_failing_silently(): + async def scenario(server, url): + held = [await connect(url) for _ in range(2)] + for ws in held: + await ws.recv() + c = MailboxClient(url, new_side(), timeout=2.0, attempts=1) + with pytest.raises(MailboxError) as refused: + await c.connect() + assert refused.value.code == "busy" + for ws in held: + await ws.close() + + run(scenario, max_connections_per_address=2) + + +def test_nameplates_are_capped_and_the_refusal_is_busy(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": new_side()})) + await ws.send(json.dumps({"type": "allocate"})) + await next_of(ws, "allocated") + await ws.send(json.dumps({"type": "allocate"})) + await next_of(ws, "allocated") + await ws.send(json.dumps({"type": "allocate"})) + refused = await next_of(ws, "error") + assert refused["code"] == "busy" + assert server.open_nameplates() == 2 + await ws.close() + + run(scenario, max_nameplates=2) + + +def test_a_connection_that_never_binds_is_closed(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await asyncio.sleep(0.6) + with pytest.raises(ConnectionClosed): + await ws.recv() + assert server.open_connections() == 0 + + run(scenario, bind_timeout=0.2) + + +def test_a_bound_connection_is_not_closed_by_the_bind_timeout(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": new_side()})) + await asyncio.sleep(0.6) + await ws.send(json.dumps({"type": "allocate"})) + assert (await next_of(ws, "allocated"))["nameplate"].isdigit() + await ws.close() + + run(scenario, bind_timeout=0.2) + + +def test_a_bad_rate_is_refused_when_the_server_is_made(): + from transferd_gui.wormhole.server import MailboxServer + + with pytest.raises(ValueError): + MailboxServer(rates={"allocate": (0.0, 1.0)}) + with pytest.raises(ValueError): + MailboxServer(rates={"allocate": (1.0, 0.0)}) diff --git a/gui/tests/test_wormhole_mailbox.py b/gui/tests/test_wormhole_mailbox.py new file mode 100644 index 0000000..f6bfb83 --- /dev/null +++ b/gui/tests/test_wormhole_mailbox.py @@ -0,0 +1,384 @@ +"""The wormhole mailbox, against the real server on 127.0.0.1: meeting on a nameplate, replay, acknowledgements, reconnection, +the limits, and expiry. Each test runs its own server and its own event loop.""" + +from __future__ import annotations + +import asyncio +import json + +import pytest +from websockets.asyncio.client import connect + +from transferd_gui.wormhole.errors import MailboxError +from transferd_gui.wormhole.keys import new_side +from transferd_gui.wormhole.mailbox import MailboxClient +from transferd_gui.wormhole.server import APP_ID, MailboxServer + + +def run(scenario, timeout: float = 20.0, *, tls=None, **server_kwargs): + """Start a server, run `scenario(server, url)`, stop the server. Returns the scenario's result. With `tls`, the server + speaks wss:// with that SSL context, and `url` is a wss:// address.""" + + async def main(): + server = MailboxServer(**server_kwargs) + port = await server.start("127.0.0.1", 0, tls=tls) + scheme = "wss" if tls is not None else "ws" + try: + return await asyncio.wait_for(scenario(server, f"{scheme}://127.0.0.1:{port}"), timeout) + finally: + await server.close() + + return asyncio.run(main()) + + +async def client(url: str, timeout: float = 5.0) -> MailboxClient: + c = MailboxClient(url, new_side(), timeout=timeout) + await c.connect() + return c + + +async def raw_session(url: str): + """A connection that speaks the wire protocol by hand, for what the client never sends.""" + ws = await connect(url) + welcome = json.loads(await ws.recv()) + return ws, welcome + + +async def next_of(ws, kind: str): + while True: + message = json.loads(await ws.recv()) + if message.get("type") == kind: + return message + + +# ----- meeting and exchanging ------------------------------------------------------------------------ + + +def test_two_sides_meet_on_a_nameplate_and_exchange_messages_both_ways(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + assert await b.claim(nameplate) == await a.claim(nameplate) + await a.open() + await b.open() + await a.add("pake", b"from a") + got = await b.receive(2) + assert (got.side, got.phase, got.body) == (a.side, "pake", b"from a") + await b.add("pake", b"from b") + back = await a.receive(2) + assert (back.side, back.body) == (b.side, b"from b") + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_a_sender_never_receives_its_own_message_back(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("pake", b"mine") + assert await a.receive(0.3) is None + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_messages_sent_before_the_other_side_opens_are_replayed_in_order(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await a.add("pake", b"first") + await a.add("version", b"second") + await b.open() + assert (await b.receive(2)).body == b"first" + assert (await b.receive(2)).body == b"second" + await a.disconnect() + await b.disconnect() + + run(scenario) + + +# ----- acknowledgements and reconnection ------------------------------------------------------------ + + +def test_an_acknowledged_message_is_not_replayed_after_a_reconnect(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("offer", b"offer") + got = await b.receive(2) + await b.ack(got.message_id) + await b.reconnect() + assert await b.receive(0.4) is None, "an acknowledged message is not sent again" + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_a_message_delivered_before_a_reconnect_is_not_delivered_twice(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("offer", b"offer") + first = await b.receive(2) + await b.reconnect() # the mailbox still holds it, since nothing acknowledged it + assert await b.receive(0.4) is None, "the caller already has it, so the replay is dropped" + await b.ack(first.message_id) + await b.reconnect() + assert await b.receive(0.4) is None + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_a_message_sent_while_disconnected_is_kept_and_sent_after_reconnect(): + async def scenario(server, url): + a = await client(url, timeout=0.5) + b = await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.disconnect() + with pytest.raises(MailboxError): + await a.add("version", b"sent while down") + await a.reconnect() + await a.flush() + got = await b.receive(2) + assert got.body == b"sent while down" + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_an_acknowledgement_sent_while_disconnected_is_sent_after_reconnect(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("offer", b"offer") + got = await b.receive(2) + await b.disconnect() + await b.ack(got.message_id) # kept, since the connection is down + await b.reconnect() + await b.open() + assert await b.receive(0.4) is None + await a.disconnect() + await b.disconnect() + + run(scenario) + + +# ----- the nameplate: crowding, release, close ------------------------------------------------------- + + +def test_a_third_computer_on_a_nameplate_is_refused_as_crowded(): + async def scenario(server, url): + a, b, c = await client(url), await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + with pytest.raises(MailboxError, match="crowded"): + await c.claim(nameplate) + for x in (a, b, c): + await x.disconnect() + + run(scenario) + + +def test_a_bad_bind_is_refused_and_the_connection_can_try_again(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": "someone-else/9", "side": new_side()})) + error = await next_of(ws, "error") + assert "this mailbox serves" in error["error"] + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": new_side()})) + await ws.send(json.dumps({"type": "allocate"})) + assert (await next_of(ws, "allocated"))["nameplate"].isdigit() + await ws.close() + + run(scenario) + + +def test_a_request_before_bind_and_an_unknown_request_are_refused(): + async def scenario(server, url): + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "allocate"})) + assert "bind before" in (await next_of(ws, "error"))["error"] + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": new_side()})) + await ws.send(json.dumps({"type": "frobnicate"})) + assert "unknown message" in (await next_of(ws, "error"))["error"] + await ws.send("not json at all") + assert "JSON object" in (await next_of(ws, "error"))["error"] + await ws.close() + + run(scenario) + + +def test_a_message_over_the_size_limit_is_refused_by_the_client_and_by_the_server(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + with pytest.raises(MailboxError, match="at most 65536 bytes"): + await a.add("pake", b"x" * 65537) + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": a.side})) + await ws.send(json.dumps({"type": "open", "mailbox": a.mailbox_id})) + await next_of(ws, "opened") + await ws.send(json.dumps({"type": "add", "mailbox": a.mailbox_id, "id": "beef", "phase": "pake", "body": "ab" * 65537})) + error = await next_of(ws, "error") + assert error["orig"] == "add" and error["id"] == "beef" + await ws.close() + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_the_mailbox_stops_taking_messages_at_its_limit(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await a.add("pake", b"1") + await a.add("version", b"2") + with pytest.raises(MailboxError, match="full"): + await a.add("identity", b"3") + await a.disconnect() + await b.disconnect() + + run(scenario, max_messages=2) + + +def test_a_retry_of_a_stored_message_is_confirmed_and_stored_once(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + ws, _welcome = await raw_session(url) + await ws.send(json.dumps({"type": "bind", "appid": APP_ID, "side": a.side})) + await ws.send(json.dumps({"type": "open", "mailbox": a.mailbox_id})) + await next_of(ws, "opened") + payload = {"type": "add", "mailbox": a.mailbox_id, "id": "c0de", "phase": "pake", "body": "00"} + await ws.send(json.dumps(payload)) + assert (await next_of(ws, "added"))["id"] == "c0de" + await ws.send(json.dumps(payload)) + assert (await next_of(ws, "added"))["id"] == "c0de" + assert (await b.receive(2)).message_id == "c0de" + assert await b.receive(0.3) is None, "the retry is not stored, so it is not delivered again" + await ws.close() + await a.disconnect() + await b.disconnect() + + run(scenario) + + +def test_releasing_the_only_side_removes_the_nameplate(): + async def scenario(server, url): + a = await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + assert server.open_mailboxes() == 1 + await a.release() + assert server.open_nameplates() == 0 + assert server.open_mailboxes() == 0 + await a.disconnect() + + run(scenario) + + +def test_both_sides_closing_removes_the_mailbox(): + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.close("happy") + assert server.open_mailboxes() == 1, "one side closing leaves the mailbox for the other" + await b.close("happy") + assert server.open_mailboxes() == 0 + + run(scenario) + + +# ----- expiry ---------------------------------------------------------------------------------------- + + +def test_an_unclaimed_nameplate_expires_and_a_claimed_one_does_not(): + now = [0.0] + + async def scenario(server, url): + a = await client(url) + await a.allocate() + b = await client(url) + nameplate = await b.allocate() + await b.claim(nameplate) + now[0] = 301.0 + server.reap() + assert server.open_nameplates() == 1, "the claimed one stays; the unclaimed one has gone" + await a.disconnect() + await b.disconnect() + + run(scenario, clock=lambda: now[0]) + + +def test_an_idle_mailbox_expires(): + now = [0.0] + + async def scenario(server, url): + a, b = await client(url), await client(url) + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + assert server.open_mailboxes() == 1 + now[0] = 3601.0 + server.reap() + assert server.open_mailboxes() == 0 + assert server.open_nameplates() == 0 + await a.disconnect() + await b.disconnect() + + run(scenario, clock=lambda: now[0]) + + +def test_nameplates_are_in_range_and_not_repeated(): + async def scenario(server, url): + c = await client(url) + numbers = [await c.allocate() for _ in range(20)] + assert len(set(numbers)) == 20 + assert all(1 <= n <= 65535 for n in numbers) + await c.disconnect() + + run(scenario) diff --git a/gui/tests/test_wormhole_protocol.py b/gui/tests/test_wormhole_protocol.py new file mode 100644 index 0000000..d6786de --- /dev/null +++ b/gui/tests/test_wormhole_protocol.py @@ -0,0 +1,179 @@ +"""The wormhole's messages: every field is checked before it is used, and a message from a stranger is refused, not repaired.""" + +from __future__ import annotations + +import hashlib + +import pytest + +from transferd.identity import HYBRID_PK_LEN, HybridIdentity +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.errors import ProtocolError + +SHA = hashlib.sha256(b"x").hexdigest() +NODE = "ab" * 32 + + +def identity_dict(**overrides): + base = { + "node_id": NODE, + "public_key": (b"\x01" * 2624).hex(), + "name": "laptop", + "relay": "", + "hints": [{"kind": "direct", "host": "192.168.1.5", "port": 53123}], + } + base.update(overrides) + return base + + +# ----- offers ---------------------------------------------------------------------------------------- + + +def test_a_file_offer_round_trips(): + offer = P.Offer.for_file("report.pdf", 1234, SHA) + assert P.Offer.from_dict(offer.to_dict()) == offer + + +def test_a_text_offer_round_trips_and_its_size_is_its_bytes(): + offer = P.Offer.for_text("héllo") + again = P.Offer.from_dict(offer.to_dict()) + assert again.text == "héllo" and again.size == len("héllo".encode("utf-8")) + + +def test_a_directory_offer_needs_its_entry_count(): + with pytest.raises(ProtocolError, match="'entries' is missing"): + P.Offer.from_dict({"kind": "directory", "name": "photos", "size": 1, "sha256": SHA}) + + +@pytest.mark.parametrize( + "name", + ["../evil", "a/b", "a\\b", "bad\x00name", " ", "", "..", "x" * 200], +) +def test_a_name_that_cannot_be_a_file_name_is_refused(name): + with pytest.raises(ProtocolError): + P.Offer.from_dict({"kind": "file", "name": name, "size": 1, "sha256": SHA}) + + +def test_an_unknown_kind_is_refused(): + with pytest.raises(ProtocolError, match="kind"): + P.Offer.from_dict({"kind": "script", "name": "x", "size": 1, "sha256": SHA}) + + +@pytest.mark.parametrize("size", [-1, True, "12", 1 << 41]) +def test_a_size_must_be_a_plain_number_in_range(size): + with pytest.raises(ProtocolError): + P.Offer.from_dict({"kind": "file", "name": "x", "size": size, "sha256": SHA}) + + +def test_a_hash_must_be_sixty_four_lower_case_hex_characters(): + with pytest.raises(ProtocolError): + P.Offer.from_dict({"kind": "file", "name": "x", "size": 1, "sha256": "ABC"}) + with pytest.raises(ProtocolError): + P.Offer.from_dict({"kind": "file", "name": "x", "size": 1, "sha256": "z" * 64}) + + +def test_a_text_longer_than_the_limit_is_refused_to_send_and_to_read(): + with pytest.raises(ProtocolError): + P.Offer.for_text("x" * (P.TEXT_MAX_BYTES + 1)) + with pytest.raises(ProtocolError): + P.Offer.from_dict({"kind": "text", "text": "x" * (P.TEXT_MAX_BYTES + 1)}) + + +def test_a_name_from_the_other_side_is_reduced_to_a_file_name_or_refused(): + assert P.safe_offered_name(" report.pdf. ") == "report.pdf" + with pytest.raises(ProtocolError): + P.safe_offered_name("C:\\Windows\\x") + + +# ----- identities ------------------------------------------------------------------------------------ + + +def test_a_real_hybrid_public_key_has_the_length_the_protocol_expects(): + identity = HybridIdentity.generate("laptop") + assert len(identity.public_key) == HYBRID_PK_LEN == 2624 + assert P.PeerIdentity.from_dict(identity_dict(public_key=identity.public_key.hex())).public_key == identity.public_key + + +def test_an_identity_round_trips_through_its_dictionary(): + peer = P.PeerIdentity.from_dict(identity_dict()) + assert peer.node_id == NODE and len(peer.public_key) == 2624 + assert P.PeerIdentity.from_dict(peer.to_dict()) == peer + + +def test_an_identity_with_a_short_key_or_bad_node_id_is_refused(): + with pytest.raises(ProtocolError): + P.PeerIdentity.from_dict(identity_dict(public_key="ab" * 10)) + with pytest.raises(ProtocolError): + P.PeerIdentity.from_dict(identity_dict(node_id="xyz")) + + +def test_an_identity_may_carry_at_most_eight_hints(): + hints = [{"kind": "direct", "host": "10.0.0.1", "port": 1000 + i} for i in range(9)] + with pytest.raises(ProtocolError, match="at most 8"): + P.PeerIdentity.from_dict(identity_dict(hints=hints)) + + +@pytest.mark.parametrize( + "hint", + [ + {"kind": "tailscale", "host": "x", "port": 1}, + {"kind": "direct", "host": "x", "port": 0}, + {"kind": "direct", "host": "x", "port": 70000}, + "not an object", + ], +) +def test_a_bad_hint_is_refused(hint): + with pytest.raises(ProtocolError): + P.PeerIdentity.from_dict(identity_dict(hints=[hint])) + + +# ----- version, answer, done ------------------------------------------------------------------------- + + +def test_our_own_version_passes_our_check(): + P.Version.ours().check() + + +def test_a_version_for_another_protocol_or_overlay_is_refused(): + ours = P.Version.ours() + with pytest.raises(ProtocolError, match="protocol 2"): + P.Version(2, P.APP, ours.overlay, ours.features).check() + with pytest.raises(ProtocolError, match="overlay"): + P.Version(ours.protocol, P.APP, ours.overlay + 1, ours.features).check() + with pytest.raises(ProtocolError, match="speaks"): + P.Version(ours.protocol, "someone-else/1", ours.overlay, ours.features).check() + + +def test_an_answer_needs_accept_as_a_boolean(): + assert P.Answer.from_dict({"accept": True}).accept is True + with pytest.raises(ProtocolError): + P.Answer.from_dict({"accept": "yes"}) + with pytest.raises(ProtocolError): + P.Answer.from_dict({}) + + +def test_a_done_message_carries_ok_and_optionally_a_hash(): + assert P.Done.from_dict({"ok": True, "sha256": SHA}).sha256 == SHA + assert P.Done.from_dict({"ok": False, "reason": "no"}).reason == "no" + with pytest.raises(ProtocolError): + P.Done.from_dict({"ok": True, "sha256": "not hex"}) + + +# ----- bytes ----------------------------------------------------------------------------------------- + + +def test_encoding_is_the_same_bytes_every_time(): + assert P.encode({"b": 1, "a": 2}) == P.encode({"a": 2, "b": 1}) == b'{"a":2,"b":1}' + + +def test_bytes_that_are_not_a_json_object_are_refused(): + for raw in (b"[1,2]", b"not json", b"\xff\xfe", b'"just a string"'): + with pytest.raises(ProtocolError): + P.decode(raw) + + +def test_a_message_over_the_size_limit_is_refused_both_ways(): + with pytest.raises(ProtocolError): + P.encode({"x": "y" * (P.JSON_MAX + 10)}) + with pytest.raises(ProtocolError): + P.decode(b"{" + b" " * P.JSON_MAX + b"}") diff --git a/gui/tests/test_wormhole_screen.py b/gui/tests/test_wormhole_screen.py new file mode 100644 index 0000000..b922170 --- /dev/null +++ b/gui/tests/test_wormhole_screen.py @@ -0,0 +1,355 @@ +"""The Wormhole screen, offscreen, with two real windows. Each window has its own service, node and backend thread, and both +meet on a real mailbox server that runs on its own loop for the length of a test. Nothing is mocked: the sends, the codes, +the handshake and the answers all go through the page's buttons and the real session code. + +Visual layout is not checked here; see gui/README.md. +""" + +from __future__ import annotations + +import asyncio +import socket +import threading +import time +from pathlib import Path + +import pytest +from PySide6.QtCore import QEvent + +from support import free_port, make_settings +from transferd_gui.backend.service import TransferdService +from transferd_gui.backend.wormhole import NO_MAILBOX +from transferd_gui.model import telemetry as telemetry_model +from transferd_gui.ui.bridge import Bridge +from transferd_gui.ui.main_window import MainWindow +from transferd_gui.wormhole.addresses import display_fingerprint +from transferd_gui.wormhole.codes import generate, parse as parse_code +from transferd_gui.wormhole.server import MailboxServer + +WAIT = 30.0 +TEXT = "hello from the sender" + + +class MailboxHost: + """The mailbox server, on a thread of its own with its own event loop.""" + + def __init__(self) -> None: + self.loop = asyncio.new_event_loop() + self.thread = threading.Thread(target=self.loop.run_forever, name="mailbox-host", daemon=True) + self.server = MailboxServer() + self.url = "" + + def start(self) -> None: + self.thread.start() + port = asyncio.run_coroutine_threadsafe(self.server.start("127.0.0.1", 0), self.loop).result(10) + self.url = f"ws://127.0.0.1:{port}" + + def stop(self) -> None: + asyncio.run_coroutine_threadsafe(self.server.close(), self.loop).result(10) + self.loop.call_soon_threadsafe(self.loop.stop) + self.thread.join(10) + self.loop.close() + + +def build_window(qapp, folder: Path, **changes): + settings_path = folder / "anchor" / "settings.json" + defaults = make_settings(folder / "app", **changes) + bridge = Bridge() + store = telemetry_model.TelemetryStore(600) + service = TransferdService(settings_path, defaults, on_snapshot=bridge.snapshot_callback, on_log=bridge.log_callback) + window = MainWindow(service, bridge, store) + return window, service + + +def dispose(qapp, window) -> None: + window.close() + window.deleteLater() + qapp.sendPostedEvents(None, QEvent.Type.DeferredDelete) + + +def pump(qapp, predicate, timeout: float = WAIT) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + qapp.processEvents() + if predicate(): + return True + time.sleep(0.02) + qapp.processEvents() + return predicate() + + +@pytest.fixture +def mailbox(): + host = MailboxHost() + host.start() + yield host + host.stop() + + +@pytest.fixture +def pair(qapp, tmp_path, mailbox): + """Two windows on one mailbox: the sender and the receiver. Each has a started service.""" + sides = {} + for name in ("sender", "receiver"): + window, service = build_window(qapp, tmp_path / name, wormhole_mailbox=mailbox.url) + service.start() + sides[name] = (window, service) + yield sides["sender"], sides["receiver"] + for window, service in sides.values(): + service.stop() + dispose(qapp, window) + + +def wormhole_page(window): + return window.page("wormhole") + + +# ----- availability ----------------------------------------------------------------------------- + + +def test_without_a_mailbox_the_screen_says_so_and_nothing_can_start(qapp, tmp_path): + window, service = build_window(qapp, tmp_path) + try: + page = wormhole_page(window) + assert page.setup_notice.text() == NO_MAILBOX + for button in (page.send_file_button, page.send_folder_button, page.send_text_button, page.look_up_button): + assert button.isEnabled() is False + assert page.code_input.isEnabled() is False + assert page.text_input.isEnabled() is False + finally: + dispose(qapp, window) + + +def test_setting_a_mailbox_enables_the_screen_once_settings_are_saved(qapp, tmp_path): + window, service = build_window(qapp, tmp_path) + try: + service.change_settings({"wormhole_mailbox": "wss://mailbox.example.net:4470"}) + window._settings_saved(service.settings) + page = wormhole_page(window) + assert page.send_text_button.isEnabled() is True + assert "mailbox.example.net:4470" in page.setup_notice.text() + finally: + dispose(qapp, window) + + +def test_empty_inputs_are_refused_without_starting_anything(qapp, pair): + (sender, _), _ = pair + page = wormhole_page(sender) + page.code_input.setText("") + page.look_up_button.click() + assert page.receive_status.text() == "Type the code first." + page.text_input.setPlainText(" ") + page.send_text_button.click() + assert page.send_status.text() == "Type a text first." + assert page.code_label.text() == "" + + +# ----- a text, end to end ----------------------------------------------------------------------- + + +def test_a_text_sent_with_a_code_is_received_once_the_receiver_accepts(qapp, pair): + (sender, _), (receiver, _) = pair + sending, receiving = wormhole_page(sender), wormhole_page(receiver) + + sending.text_input.setPlainText(TEXT) + sending.send_text_button.click() + assert pump(qapp, lambda: sending.code_label.text() != "") + code = sending.code_label.text() + assert parse_code(code).nameplate >= 1 + + receiving.code_input.setText(code) + receiving.look_up_button.click() + assert pump(qapp, lambda: receiving.accept_button.isEnabled() and receiving.offer_label.text() != "") + assert receiving.offer_label.text() == f"A text of {len(TEXT.encode())} bytes is offered." + + receiving.accept_button.click() + assert pump(qapp, lambda: not receiving.received_text.isHidden()) + assert receiving.received_text.toPlainText() == TEXT + assert receiving.receive_status.text() == "Received a text." + assert pump(qapp, lambda: sending.send_status.text() == "Sent.") + assert sending.code_label.text() == "" + assert sending.cancel_send_button.isEnabled() is False + + +# ----- refusals and stopping -------------------------------------------------------------------- + + +def test_declining_tells_the_sender_and_writes_nothing(qapp, pair): + (sender, _), (receiver, service) = pair + sending, receiving = wormhole_page(sender), wormhole_page(receiver) + + sending.send_text("no thank you") + assert pump(qapp, lambda: sending.code_label.text() != "") + receiving.code_input.setText(sending.code_label.text()) + receiving.look_up_button.click() + assert pump(qapp, lambda: receiving.decline_button.isEnabled()) + + receiving.decline_button.click() + assert pump(qapp, lambda: receiving.receive_status.text() == "Declined.") + assert pump(qapp, lambda: sending.send_status.text().startswith("Declined by the other computer.")) + assert "the receiving user declined" in sending.send_status.text() + download = Path(service.settings.download_dir) + assert not download.exists() or not any(download.iterdir()) + + +def test_stopping_while_the_offer_waits_declines_it_and_the_sender_is_told(qapp, pair): + (sender, _), (receiver, _) = pair + sending, receiving = wormhole_page(sender), wormhole_page(receiver) + + sending.send_text("stop me") + assert pump(qapp, lambda: sending.code_label.text() != "") + receiving.code_input.setText(sending.code_label.text()) + receiving.look_up_button.click() + assert pump(qapp, lambda: receiving.decline_button.isEnabled()) + + receiving.stop_receive_button.click() + assert receiving.receive_status.text() == "Stopped. The offer was declined." + assert pump(qapp, lambda: sending.send_status.text().startswith("Declined by the other computer.")) + assert "stopped by the receiving user" in sending.send_status.text() + + +def test_a_wrong_code_is_refused_on_both_sides(qapp, pair): + (sender, _), (receiver, _) = pair + sending, receiving = wormhole_page(sender), wormhole_page(receiver) + + sending.send_text(TEXT) + assert pump(qapp, lambda: sending.code_label.text() != "") + right = parse_code(sending.code_label.text()) + wrong = generate(right.nameplate, lambda n: bytes([7]) * n) + assert str(wrong) != str(right) + + receiving.code_input.setText(str(wrong)) + receiving.look_up_button.click() + assert pump(qapp, lambda: "wrong" in receiving.receive_status.text().lower()) + assert receiving.accept_button.isEnabled() is False + assert pump(qapp, lambda: "wrong" in sending.send_status.text().lower()) + assert sending.code_label.text() == "" + + +# ----- cancelling ------------------------------------------------------------------------------- + + +def test_cancelling_a_send_clears_the_code_and_a_new_send_can_start(qapp, pair): + (sender, _), _ = pair + page = wormhole_page(sender) + + page.send_text(TEXT) + assert pump(qapp, lambda: page.code_label.text() != "") + page.send_text("second, while the first is waiting") + assert "already in progress" in page.send_status.text() + + page.cancel_send_button.click() + assert page.code_label.text() == "" + assert page.cancel_send_button.isEnabled() is False + assert page.send_status.text().startswith("Cancelled.") + + page.send_text("after the cancel") + assert pump(qapp, lambda: page.code_label.text() != "") + assert page.send_status.text() == "Waiting for the other computer to type this code." + page.cancel_send_button.click() + assert page.code_label.text() == "" + + +# ----- the mailbox card and hosting ------------------------------------------------------------------- + + +def test_hosting_on_this_computer_gives_a_working_mailbox_with_no_list(qapp, tmp_path): + port = free_port() + window, service = build_window(qapp, tmp_path) + service.start() + try: + service.change_settings({"wormhole_host": True, "wormhole_host_port": port}) + page = wormhole_page(window) + # The page reads the hosting state when the log reports it, so wait for the page rather than the backend. + assert pump(qapp, lambda: page.setup_notice.text() == f"The mailbox is ws://127.0.0.1:{port}."), page.setup_notice.text() + assert page.send_text_button.isEnabled() is True + assert "for this computer only" in page.host_notice.text() + assert page.share_edit.isHidden(), "a mailbox on this computer alone has no share line" + page.send_text(TEXT) + assert pump(qapp, lambda: page.code_label.text() != "") + page.cancel_send_button.click() + finally: + service.stop() + dispose(qapp, window) + + +def test_hosting_on_the_network_shows_the_fingerprint_and_the_share_line(qapp, tmp_path): + port = free_port() + window, service = build_window(qapp, tmp_path) + service.start() + # The app listens on every interface; this test keeps the mailbox to this computer. + service.mailbox_host._network_bind = "127.0.0.1" + try: + service.change_settings({"wormhole_host": True, "wormhole_host_port": port, "wormhole_host_network": True}) + page = wormhole_page(window) + assert pump(qapp, lambda: page.share_edit.text() != "") + status = service.mailbox_host.status() + assert display_fingerprint(status.fingerprint) in page.host_notice.text() + assert page.share_edit.isHidden() is False + share = page.share_edit.text() + assert share.startswith("wss://") and f":{port}#" in share + assert share.endswith("#" + status.fingerprint) + assert page.setup_notice.text() == f"The mailbox is wss://127.0.0.1:{port}#{status.fingerprint}." + finally: + service.stop() + dispose(qapp, window) + + +def test_turning_hosting_off_removes_the_share_line_and_the_mailbox(qapp, tmp_path): + port = free_port() + window, service = build_window(qapp, tmp_path) + service.start() + service.mailbox_host._network_bind = "127.0.0.1" + try: + service.change_settings({"wormhole_host": True, "wormhole_host_port": port, "wormhole_host_network": True}) + assert pump(qapp, lambda: service.mailbox_host.status().running) + page = wormhole_page(window) + service.change_settings({"wormhole_host": False}) + assert pump(qapp, lambda: not service.mailbox_host.status().running) + assert pump(qapp, lambda: page.share_edit.isHidden()) + assert page.setup_notice.text() == NO_MAILBOX + assert "not hosting a mailbox" in page.host_notice.text() + finally: + service.stop() + dispose(qapp, window) + + +def test_a_port_already_in_use_is_shown_on_the_screen(qapp, tmp_path): + port = free_port() + blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + blocker.bind(("127.0.0.1", port)) + blocker.listen() + window, service = build_window(qapp, tmp_path) + service.start() + try: + service.change_settings({"wormhole_host": True, "wormhole_host_port": port}) + page = wormhole_page(window) + assert pump(qapp, lambda: f"could not listen on port {port}" in page.host_notice.text()) + assert page.setup_notice.text() == NO_MAILBOX + finally: + blocker.close() + service.stop() + dispose(qapp, window) + + +def test_the_settings_page_saves_the_hosting_choice_and_refuses_a_bad_mailbox(qapp, tmp_path): + port = free_port() + window, service = build_window(qapp, tmp_path) + service.start() + try: + settings_page = window.page("settings") + settings_page.wormhole_mailbox.setText("ws://mailbox.example.net:4470") + settings_page.save_button.click() + assert "reaches only this computer" in settings_page.notice.text() + assert service.settings.wormhole_mailbox == "" + + settings_page.wormhole_mailbox.setText("") + settings_page.wormhole_host.setChecked(True) + settings_page.wormhole_host_port.setValue(port) + settings_page.save_button.click() + assert service.settings.wormhole_host is True + assert service.settings.wormhole_host_port == port + assert pump(qapp, lambda: service.mailbox_host.status().running) + finally: + service.stop() + dispose(qapp, window) diff --git a/gui/tests/test_wormhole_session.py b/gui/tests/test_wormhole_session.py new file mode 100644 index 0000000..20c1cbb --- /dev/null +++ b/gui/tests/test_wormhole_session.py @@ -0,0 +1,305 @@ +"""The wormhole's two sides, run against each other through the real mailbox server, with an in-memory transit so the state +machine is tested without the overlay. The overlay transit is tested with the endpoint.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Dict + +import pytest + +from test_wormhole_mailbox import run +from transferd.identity import HYBRID_PK_LEN +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole import session +from transferd_gui.wormhole.codes import Code +from transferd_gui.wormhole.errors import OpenError, TimedOut, TransferError +from transferd_gui.wormhole.session import Receiver, Sender +from transferd_gui.wormhole.transfer import prepare_file, prepare_folder + + +class Hub: + """The bytes that the in-memory transit carries from the sender to the receiver.""" + + def __init__(self) -> None: + self.data: Dict[str, bytes] = {} + self.ready = asyncio.Event() + + +class MemoryTransit: + def __init__(self, hub: Hub, name: str) -> None: + self.hub = hub + self.closed = False + self._identity = P.PeerIdentity("ab" * 32, b"\x01" * HYBRID_PK_LEN, name, "", ()) + + def local_identity(self) -> P.PeerIdentity: + return self._identity + + def expect_peer(self, peer: P.PeerIdentity) -> None: + self.expected = peer + + async def open(self) -> None: + return None + + async def send(self, peer, offer, source: Path) -> None: + self.hub.data[offer.name] = source.read_bytes() + self.hub.ready.set() + + async def receive(self, peer, offer, folder: Path) -> Path: + await asyncio.wait_for(self.hub.ready.wait(), 10) + path = folder / offer.name + path.write_bytes(self.hub.data[offer.name]) + return path + + async def close(self) -> None: + self.closed = True + + +def pair(url: str, offer: P.Offer, source=None, *, answer_timeout: float = 10.0): + hub = Hub() + sender = Sender(url, transit=MemoryTransit(hub, "sender"), offer=offer, source=source, answer_timeout=answer_timeout) + return sender, hub + + +async def connected_receiver(url: str, code: Code, hub: Hub) -> Receiver: + receiver = Receiver(url, code, transit=MemoryTransit(hub, "receiver")) + await receiver.connect() + return receiver + + +# ----- transfers ------------------------------------------------------------------------------------- + + +def test_a_text_is_offered_accepted_and_arrives_with_no_transit(tmp_path): + def scenario(server, url): + async def go(): + offer = P.Offer.for_text("hello, there") + sender, hub = pair(url, offer) + code = await sender.start() + + async def receiving(): + receiver = await connected_receiver(url, code, hub) + got = await receiver.offer() + assert got.kind == "text" and got.text == "hello, there" + await receiver.answer(True) + return await receiver.finish(tmp_path) + + send_result, receive_result = await asyncio.gather(sender.run(), receiving()) + assert send_result.ok and not send_result.declined + assert receive_result.kind == "text" and receive_result.text == "hello, there" + assert not hub.data, "a text never travels over the transit" + return server.close_moods + + return go() + + moods = run(scenario) + assert moods == ["happy", "happy"], "both sides close the mailbox happy" + + +def test_a_file_arrives_with_the_same_bytes_and_its_hash_is_checked(tmp_path): + source = tmp_path / "report.bin" + source.write_bytes(bytes(range(256)) * 1000) + offer, path = prepare_file(source) + folder = tmp_path / "downloads" + folder.mkdir() + + def scenario(server, url): + async def go(): + sender, hub = pair(url, offer, path) + code = await sender.start() + + async def receiving(): + receiver = await connected_receiver(url, code, hub) + assert (await receiver.offer()).kind == "file" + await receiver.answer(True) + return await receiver.finish(folder) + + send_result, receive_result = await asyncio.gather(sender.run(), receiving()) + assert send_result.ok + return receive_result + + return go() + + result = run(scenario) + assert result.kind == "file" + assert result.path.read_bytes() == source.read_bytes() + assert result.sha256 == offer.sha256 + + +def test_a_folder_arrives_as_the_same_tree(tmp_path): + tree = tmp_path / "photos" + (tree / "2026" / "may").mkdir(parents=True) + (tree / "readme.txt").write_text("hello", encoding="utf-8") + (tree / "2026" / "may" / "a.bin").write_bytes(b"\x00\x01" * 4096) + scratch = tmp_path / "scratch" + scratch.mkdir() + offer, archive = prepare_folder(tree, scratch) + folder = tmp_path / "downloads" + folder.mkdir() + + def scenario(server, url): + async def go(): + sender, hub = pair(url, offer, archive) + code = await sender.start() + + async def receiving(): + receiver = await connected_receiver(url, code, hub) + assert (await receiver.offer()).kind == "directory" + await receiver.answer(True) + return await receiver.finish(folder) + + send_result, receive_result = await asyncio.gather(sender.run(), receiving()) + assert send_result.ok + return receive_result + + return go() + + result = run(scenario) + assert result.kind == "directory" + assert result.path.name == "photos" + assert (result.path / "readme.txt").read_text(encoding="utf-8") == "hello" + assert (result.path / "2026" / "may" / "a.bin").read_bytes() == b"\x00\x01" * 4096 + assert not archive.exists() or archive.parent == scratch + assert not any(p.name.endswith(".zip") for p in folder.iterdir()), "the archive is not left in the download folder" + + +def test_a_declined_offer_tells_the_sender_and_sends_nothing(tmp_path): + source = tmp_path / "x.bin" + source.write_bytes(b"secret") + offer, path = prepare_file(source) + hubs = [] + + def scenario(server, url): + async def go(): + sender, hub = pair(url, offer, path) + hubs.append(hub) + code = await sender.start() + + async def receiving(): + receiver = await connected_receiver(url, code, hub) + await receiver.offer() + await receiver.answer(False, "not now") + return await receiver.finish(tmp_path / "downloads") + + return await asyncio.gather(sender.run(), receiving()) + + return go() + + send_result, receive_result = run(scenario) + assert send_result.declined and not send_result.ok + assert send_result.reason == "not now" + assert receive_result.kind == "declined" + assert not hubs[0].data, "nothing was sent over the transit" + assert not (tmp_path / "downloads").exists() or not any((tmp_path / "downloads").iterdir()) + + +# ----- refusals and failures ------------------------------------------------------------------------- + + +def test_a_wrong_code_is_refused_on_both_sides_and_closes_scary(tmp_path): + def scenario(server, url): + async def go(): + offer = P.Offer.for_text("hi") + sender, hub = pair(url, offer) + code = await sender.start() + wrong = Code(code.nameplate, bytes((b + 1) % 256 for b in code.secret)) + + async def receiving(): + receiver = Receiver(url, wrong, transit=MemoryTransit(hub, "receiver")) + await receiver.connect() + + results = await asyncio.gather(sender.run(), receiving(), return_exceptions=True) + return results, server.close_moods + + return go() + + results, moods = run(scenario) + assert isinstance(results[0], OpenError), "the sender sees the wrong code when the receiver's version does not open" + assert isinstance(results[1], OpenError) + assert moods.count("scary") == 2, "both sides close the mailbox as scary" + + +def test_a_sender_whose_receiver_never_comes_times_out_as_lonely(tmp_path, monkeypatch): + monkeypatch.setattr(session, "PAKE_TIMEOUT_S", 0.6) + monkeypatch.setattr(session, "PHASE_TIMEOUT_S", 0.6) + + def scenario(server, url): + async def go(): + sender, _hub = pair(url, P.Offer.for_text("hi")) + await sender.start() + with pytest.raises(TimedOut): + await sender.run() + return server.close_moods + + return go() + + assert run(scenario) == ["lonely"] + + +def test_a_receiver_that_never_answers_makes_the_sender_wait_then_stop(tmp_path): + def scenario(server, url): + async def go(): + hub = Hub() + sender = Sender(url, transit=MemoryTransit(hub, "sender"), offer=P.Offer.for_text("hi"), answer_timeout=0.8) + code = await sender.start() + send_task = asyncio.ensure_future(sender.run()) + receiver = await connected_receiver(url, code, hub) + # The receiver reads the offer, and never answers it. + reading = asyncio.ensure_future(receiver.offer()) + with pytest.raises(TimedOut): + await send_task + reading.cancel() + return server.close_moods + + return go() + + assert run(scenario) == ["lonely"], "the sender gave up waiting for an answer; the mailbox closed lonely" + + +def test_an_offer_that_does_not_match_the_received_bytes_is_removed_and_reported(tmp_path): + source = tmp_path / "good.bin" + source.write_bytes(b"the real bytes") + offer, path = prepare_file(source) + folder = tmp_path / "downloads" + folder.mkdir() + + class Tampering(MemoryTransit): + async def receive(self, peer, offer, folder: Path) -> Path: + await asyncio.wait_for(self.hub.ready.wait(), 10) + target = folder / offer.name + target.write_bytes(b"something else") + return target + + def scenario(server, url): + async def go(): + hub = Hub() + sender = Sender(url, transit=MemoryTransit(hub, "sender"), offer=offer, source=path) + code = await sender.start() + # The sender runs alongside the receiver, since each phase waits for the other side. + send_task = asyncio.ensure_future(sender.run()) + receiver = Receiver(url, code, transit=Tampering(hub, "receiver")) + await receiver.connect() + await receiver.offer() + await receiver.answer(True) + with pytest.raises(TransferError, match="does not match"): + await receiver.finish(folder) + with pytest.raises(TransferError): + await send_task + return list(folder.iterdir()) + + return go() + + assert run(scenario) == [], "the bad file is removed, and nothing is left in the folder" + + +def test_the_code_must_be_started_before_it_runs(): + def scenario(server, url): + async def go(): + sender, _hub = pair(url, P.Offer.for_text("x")) + with pytest.raises(Exception, match="start"): + await sender.run() + + return go() + + run(scenario) diff --git a/gui/tests/test_wormhole_tls.py b/gui/tests/test_wormhole_tls.py new file mode 100644 index 0000000..aa57c9e --- /dev/null +++ b/gui/tests/test_wormhole_tls.py @@ -0,0 +1,186 @@ +"""The mailbox over TLS, and the client's choices of mailbox: a pinned certificate meets and passes messages, a wrong pin is refused +before anything is sent, a plain connection to another computer is refused, a mailbox with no pin must have a certificate the +system trusts, the client keeps trying while a mailbox starts, it passes over a mailbox that is down, and after it has +connected it stays on that mailbox.""" + +from __future__ import annotations + +import asyncio +import socket + +import pytest + +from transferd_gui.wormhole import tls +from transferd_gui.wormhole.addresses import MailboxAddress +from transferd_gui.wormhole.errors import MailboxError +from transferd_gui.wormhole.keys import new_side +from transferd_gui.wormhole.mailbox import MailboxClient +from transferd_gui.wormhole.server import MailboxServer +from test_wormhole_mailbox import run + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def _port_of(url: str) -> int: + return int(url.rsplit(":", 1)[1]) + + +@pytest.fixture +def identity(tmp_path): + return tls.load_or_create(tmp_path / "mailbox") + + +# ----- the certificate -------------------------------------------------------------------------------- + + +def test_the_identity_is_kept_between_runs(tmp_path): + first = tls.load_or_create(tmp_path) + again = tls.load_or_create(tmp_path) + assert again.fingerprint == first.fingerprint + assert len(first.fingerprint) == 64 + assert first.cert_path.exists() and first.key_path.exists() + + +def test_the_identity_is_made_again_when_its_key_no_longer_matches_it(tmp_path): + first = tls.load_or_create(tmp_path) + _cert, other_key = tls._make() + (tmp_path / tls.KEY_FILE).write_bytes(other_key) + fresh = tls.load_or_create(tmp_path) + assert fresh.fingerprint != first.fingerprint + + +def test_the_identity_is_made_again_when_it_is_near_its_end(tmp_path, monkeypatch): + monkeypatch.setattr(tls, "VALID_DAYS", 1) # ends inside the renewal window, so the next start makes a new one + short = tls.load_or_create(tmp_path) + monkeypatch.undo() + renewed = tls.load_or_create(tmp_path) + assert renewed.fingerprint != short.fingerprint + + +# ----- meeting over TLS ------------------------------------------------------------------------------- + + +def test_a_pinned_mailbox_meets_and_passes_messages_over_wss(identity): + async def scenario(server, url): + pinned = f"{url}#{identity.fingerprint}" + a = MailboxClient(pinned, new_side(), timeout=5) + b = MailboxClient(pinned, new_side(), timeout=5) + await a.connect() + await b.connect() + assert a.url == url + nameplate = await a.allocate() + await a.claim(nameplate) + await b.claim(nameplate) + await a.open() + await b.open() + await a.add("pake", b"over tls") + got = await b.receive(2) + assert got.body == b"over tls" + await a.disconnect() + await b.disconnect() + + run(scenario, tls=tls.server_context(identity)) + + +def test_a_pin_that_is_not_the_servers_is_refused_before_anything_is_sent(identity): + async def scenario(server, url): + other = tls.fingerprint_of(b"a certificate that is not this one") + c = MailboxClient(f"{url}#{other}", new_side(), timeout=5, attempts=1) + with pytest.raises(MailboxError, match="not the one pinned"): + await c.connect() + assert server.open_nameplates() == 0 + assert server.open_mailboxes() == 0 + + run(scenario, tls=tls.server_context(identity)) + + +def test_a_mailbox_with_no_pin_must_present_a_certificate_the_system_trusts(identity): + async def scenario(server, url): + c = MailboxClient(url, new_side(), timeout=5, attempts=1) + with pytest.raises(MailboxError, match="certificate this computer accepts"): + await c.connect() + + run(scenario, tls=tls.server_context(identity)) + + +def test_the_mailbox_command_will_not_serve_the_network_without_tls(capsys): + from transferd_gui.wormhole.server import main + + assert main(["--host", "0.0.0.0", "--port", "0"]) == 2 + assert "must be served over TLS" in capsys.readouterr().err + + +def test_plain_ws_to_another_computer_is_refused_without_connecting(): + c = MailboxClient([MailboxAddress("ws", "mailbox.example.net", 4470)], new_side(), timeout=1, attempts=1) + with pytest.raises(MailboxError, match="reaches only this computer"): + asyncio.run(c.connect()) + + +# ----- which mailbox, and when -------------------------------------------------------------------------- + + +def test_the_client_keeps_trying_until_a_mailbox_that_starts_late_answers(): + port = _free_port() + + async def main(): + server = MailboxServer() + + async def start_late(): + await asyncio.sleep(0.4) + await server.start("127.0.0.1", port) + + starter = asyncio.ensure_future(start_late()) + c = MailboxClient( + f"ws://127.0.0.1:{port}", new_side(), timeout=1, attempts=60, backoff=0.02, backoff_cap=0.1 + ) + try: + await c.connect() + assert await c.allocate() > 0 + await c.disconnect() + finally: + await starter + await server.close() + + asyncio.run(main()) + + +def test_a_mailbox_that_is_down_is_passed_over_for_the_next_one_in_the_list(): + async def scenario(server, url): + dead = f"ws://127.0.0.1:{_free_port()}" + c = MailboxClient(f"{dead}, {url}", new_side(), timeout=1, attempts=1) + await c.connect() + assert c.url == url + await c.disconnect() + + run(scenario) + + +def test_after_connecting_a_client_stays_on_its_mailbox_and_does_not_move_to_another(): + async def scenario(server, url): + second = MailboxServer() + second_port = await second.start("127.0.0.1", 0) + try: + c = MailboxClient( + [ + MailboxAddress("ws", "127.0.0.1", _port_of(url), ""), + MailboxAddress("ws", "127.0.0.1", second_port, ""), + ], + new_side(), + timeout=1, + attempts=2, + backoff=0.01, + ) + await c.connect() + assert c.url == url + await server.close() # the mailbox the meeting is on goes away + with pytest.raises(MailboxError): + await c.reconnect() + assert c.url == url, "a reconnect never moves to another mailbox: the meeting is on this one" + finally: + await second.close() + + run(scenario) diff --git a/gui/tests/test_wormhole_transfer.py b/gui/tests/test_wormhole_transfer.py new file mode 100644 index 0000000..d104aeb --- /dev/null +++ b/gui/tests/test_wormhole_transfer.py @@ -0,0 +1,184 @@ +"""Folders and files for a wormhole: a folder is zipped and unpacked, and an archive that is not safe is refused whole.""" + +from __future__ import annotations + +import hashlib +import stat +import zipfile +from pathlib import Path + +import pytest + +from transferd_gui.wormhole.errors import TransferError +from transferd_gui.wormhole.transfer import ( + place_file, + prepare_file, + prepare_folder, + sha256_file, + unpack_folder, + zip_folder, +) + + +def archive(path: Path, members) -> Path: + """Write an archive with exactly these members: (name, bytes, external_attr or None). + + The name is set after the ZipInfo is made, because ZipInfo rewrites a backslash to a slash on Windows, and a hostile + archive from another tool can carry one. Members are deflated, as an archive from a real zip tool would be.""" + with zipfile.ZipFile(path, "w") as zf: + for name, data, attr in members: + info = zipfile.ZipInfo("placeholder") + info.filename = name + info.compress_type = zipfile.ZIP_DEFLATED + if attr is not None: + info.external_attr = attr + zf.writestr(info, data) + return path + + +def setup(tmp_path: Path): + folder = tmp_path / "downloads" + folder.mkdir() + scratch = tmp_path / "scratch" + scratch.mkdir() + return folder, scratch + + +def test_a_folder_zips_and_unpacks_to_the_same_tree(tmp_path): + tree = tmp_path / "trip" + (tree / "day 1").mkdir(parents=True) + (tree / "notes.txt").write_text("hi", encoding="utf-8") + (tree / "day 1" / "a.jpg").write_bytes(b"\xff" * 5000) + folder, scratch = setup(tmp_path) + offer, archive_path = prepare_folder(tree, scratch) + assert offer.kind == "directory" and offer.entries == 3 # 'day 1/', 'day 1/a.jpg', 'notes.txt' + result = unpack_folder(archive_path, folder, offer.name, expected_entries=offer.entries) + assert result.name == "trip" + assert (result / "notes.txt").read_text(encoding="utf-8") == "hi" + assert (result / "day 1" / "a.jpg").read_bytes() == b"\xff" * 5000 + + +def test_an_existing_folder_with_the_same_name_is_not_overwritten(tmp_path): + folder, scratch = setup(tmp_path) + (folder / "trip").mkdir() + (folder / "trip" / "mine.txt").write_text("keep", encoding="utf-8") + tree = tmp_path / "trip" + tree.mkdir() + (tree / "theirs.txt").write_text("new", encoding="utf-8") + offer, archive_path = prepare_folder(tree, scratch) + result = unpack_folder(archive_path, folder, offer.name, expected_entries=offer.entries) + assert result.name == "trip (2)" + assert (folder / "trip" / "mine.txt").read_text(encoding="utf-8") == "keep" + + +def test_a_name_with_dots_keeps_them_for_a_folder(tmp_path): + folder, scratch = setup(tmp_path) + tree = tmp_path / "v1.2" + tree.mkdir() + (tree / "x.txt").write_text("x", encoding="utf-8") + offer, archive_path = prepare_folder(tree, scratch) + result = unpack_folder(archive_path, folder, offer.name, expected_entries=offer.entries) + assert result.name == "v1.2" + + +@pytest.mark.parametrize( + "member", + ["../evil.txt", "a/../../evil.txt", "/abs.txt", "dir\\evil.txt", "C:evil.txt", "a//b.txt", "./x.txt"], +) +def test_an_archive_with_an_unsafe_name_is_refused_and_leaves_nothing_behind(tmp_path, member): + folder, scratch = setup(tmp_path) + bad = archive(scratch / "bad.zip", [("ok.txt", b"x", None), (member, b"evil", None)]) + with pytest.raises(TransferError): + unpack_folder(bad, folder, "bundle", expected_entries=2) + assert list(folder.iterdir()) == [], "a refused folder leaves nothing in the download folder" + assert not (tmp_path / "evil.txt").exists() + + +def test_a_link_inside_an_archive_is_refused(tmp_path): + folder, scratch = setup(tmp_path) + link_attr = (stat.S_IFLNK | 0o777) << 16 + bad = archive(scratch / "link.zip", [("pointer", b"/etc/passwd", link_attr)]) + with pytest.raises(TransferError, match="link"): + unpack_folder(bad, folder, "bundle", expected_entries=1) + assert list(folder.iterdir()) == [] + + +def test_a_device_or_fifo_inside_an_archive_is_refused(tmp_path): + folder, scratch = setup(tmp_path) + fifo_attr = (stat.S_IFIFO | 0o644) << 16 + bad = archive(scratch / "fifo.zip", [("pipe", b"", fifo_attr)]) + with pytest.raises(TransferError, match="not a file or a folder"): + unpack_folder(bad, folder, "bundle", expected_entries=1) + + +def test_an_archive_with_a_different_entry_count_than_offered_is_refused(tmp_path): + folder, scratch = setup(tmp_path) + good = archive(scratch / "two.zip", [("a", b"1", None), ("b", b"2", None)]) + with pytest.raises(TransferError, match="number of entries"): + unpack_folder(good, folder, "bundle", expected_entries=5) + assert list(folder.iterdir()) == [] + + +def test_an_archive_that_compresses_too_well_is_refused_as_a_bomb(tmp_path): + folder, scratch = setup(tmp_path) + bomb = archive(scratch / "bomb.zip", [("zeros.bin", b"\x00" * (20 * 1024 * 1024), None)]) + with pytest.raises(TransferError, match="compresses too well"): + unpack_folder(bomb, folder, "bundle", expected_entries=1) + assert list(folder.iterdir()) == [] + + +def test_a_file_that_is_not_a_zip_is_refused_and_leaves_nothing(tmp_path): + folder, scratch = setup(tmp_path) + junk = scratch / "junk.zip" + junk.write_bytes(b"this is not a zip archive") + with pytest.raises(TransferError, match="could not be unpacked"): + unpack_folder(junk, folder, "bundle", expected_entries=1) + assert list(folder.iterdir()) == [] + + +def test_a_file_is_offered_with_its_size_and_hash(tmp_path): + source = tmp_path / "data.bin" + source.write_bytes(b"hello world" * 100) + offer, path = prepare_file(source) + assert offer.kind == "file" and offer.name == "data.bin" + assert offer.size == len(b"hello world" * 100) + assert offer.sha256 == hashlib.sha256(b"hello world" * 100).hexdigest() + assert path == source + + +def test_a_missing_file_or_folder_cannot_be_offered(tmp_path): + with pytest.raises(TransferError): + prepare_file(tmp_path / "nope.txt") + with pytest.raises(TransferError): + prepare_folder(tmp_path / "nope", tmp_path) + + +def test_placing_a_file_never_overwrites(tmp_path): + folder, scratch = setup(tmp_path) + (folder / "x.txt").write_text("old", encoding="utf-8") + incoming = scratch / "incoming" + incoming.write_text("new", encoding="utf-8") + placed = place_file(incoming, folder, "x.txt") + assert placed.name == "x (2).txt" + assert (folder / "x.txt").read_text(encoding="utf-8") == "old" + assert placed.read_text(encoding="utf-8") == "new" + + +def test_the_sha256_of_a_file_matches_hashlib(tmp_path): + data = b"\x00\x01\x02" * 300_000 + path = tmp_path / "big.bin" + path.write_bytes(data) + assert sha256_file(path) == hashlib.sha256(data).hexdigest() + + +def test_a_folder_zipped_for_sending_lists_every_entry(tmp_path): + tree = tmp_path / "tree" + (tree / "sub").mkdir(parents=True) + (tree / "sub" / "f.txt").write_text("f", encoding="utf-8") + (tree / "top.txt").write_text("t", encoding="utf-8") + dest = tmp_path / "out.zip" + count = zip_folder(tree, dest) + with zipfile.ZipFile(dest) as zf: + names = sorted(zf.namelist()) + assert count == len(names) == 3, "the folder 'sub', its file, and the top file" + assert "sub/" in names and "sub/f.txt" in names and "top.txt" in names diff --git a/gui/transferd_gui/backend/debugnode.py b/gui/transferd_gui/backend/debugnode.py new file mode 100644 index 0000000..e7767ba --- /dev/null +++ b/gui/transferd_gui/backend/debugnode.py @@ -0,0 +1,494 @@ +"""The debugging part of the node: the device's agent, the computer's client operations, and the routes that carry them. + +`Node` inherits from `DebugNodeMixin`, so everything here runs on the node's asyncio loop and reads the node's own state +(peers, settings, the event log). The protocol lives in `transferd_gui.debug`; this module connects it to overlay +sessions and to the USB bridge. + +Two roles, one node: + +* as a device (the agent), it answers debug streams from the computers on its debugger list, under its policy; +* as a computer (the client), it runs operations against the device it has chosen, over Wi-Fi, the relay, and USB. +""" + +from __future__ import annotations + +import asyncio +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +from transferd.errors import Denied, NoSuchService, TransferdError, Unreachable +from transferd.frames import ServiceInfo +from transferd.handshake import handshake_initiator +from transferd.link import Link, RouteKind, TcpLink +from transferd.overlay import OverlaySession + +from transferd_gui.backend.errors import NodeError, describe +from transferd_gui.backend.files import FILE_SERVICE, STREAM_SERVICE +from transferd_gui.debug import wire +from transferd_gui.debug.agent import DebugAgent +from transferd_gui.debug.client import DebugClient, DebugError, bridge +from transferd_gui.debug.policy import DebugPolicy, parse_clients, parse_ports +from transferd_gui.debug.providers import SystemProviders +from transferd_gui.debug.stream import Channel, ChannelReset +from transferd_gui.debug.usb import Adb, AdbDevice, AdbError, free_local_port +from transferd_gui.model.settings import Settings, parse_host_port +from transferd_gui.model.snapshot import DebugSnapshot, DebugStreamSnapshot, UsbDeviceSnapshot + +SOURCE_DEBUG = "debug" +#: How often the USB bridge looks for the chosen device. +USB_SCAN_S = 5.0 +#: How long the USB bridge waits after a failed attempt before it tries again. +USB_RETRY_S = 30.0 +#: Finished debug streams kept for the Debug screen. +FINISHED_KEPT = 20 + + +class OverlayChannel: + """A debug channel over one overlay stream of a session. + + `end` is a half-close: an empty send with FIN, so the other side still reads what it is sending back (a forward's + reply, for example). `close` releases the stream fully. The overlay closes a stream by flushing it first, so `reset` + cannot skip the flush; every debug error is therefore sent in-band, as an `error` message before the end. + """ + + def __init__(self, session: OverlaySession, stream: int) -> None: + self._session = session + self._stream = stream + self._sent_end = False + self._closed = False + + async def read(self) -> Optional[bytes]: + if self._closed: + return None + try: + return await self._session.recv(self._stream) + except Exception as exc: + raise ChannelReset(describe(exc)) from exc + + async def write(self, data: bytes) -> None: + try: + await self._session.send(self._stream, data) + except Exception as exc: + raise ChannelReset(describe(exc)) from exc + + async def end(self) -> None: + if self._sent_end: + return + self._sent_end = True + try: + await self._session.send(self._stream, b"", fin=True) + except Exception: + pass # the session is gone; there is nothing left to end + + async def close(self) -> None: + if self._closed: + return + self._closed = True + try: + await self._session.close(self._stream) + except Exception: + pass # already gone; closing a finished stream is not an error + + async def reset(self, reason: str) -> None: + await self.close() + + +@dataclass +class _Handle: + """One debug operation this node is running as a computer.""" + + handle: int + peer_id: str + kind: str + detail: str + started_at: float + state: str = "running" + note: str = "" + task: Optional[asyncio.Task] = None + server: Optional[asyncio.base_events.Server] = None + tasks: Set[asyncio.Task] = field(default_factory=set) + + +def policy_from_settings(settings: Settings) -> DebugPolicy: + """The device policy the settings describe. Settings are validated before they reach here.""" + return DebugPolicy( + enabled=settings.debug_enabled, + modes={ + "info": settings.debug_info_mode, + "logcat": settings.debug_logcat_mode, + "shell": settings.debug_shell_mode, + "forward": settings.debug_forward_mode, + }, + clients=parse_clients(settings.debug_clients), + forward_ports=parse_ports(settings.debug_forward_ports), + shell_timeout_s=settings.debug_shell_timeout_s, + shell_output_limit=settings.debug_shell_output_kib * 1024, + streams_per_client=settings.debug_streams_per_client, + ) + + +class DebugNodeMixin: + """The debugging methods of `Node`. Relies on the node's `_settings`, `_peers`, `_pending`, `_log`, `_spawn`, + `_start_peer`, `_observe_link`, `_require_ready_peer`, `_await_ready` and `identity`.""" + + # ----- setup and state ---------------------------------------------------------------------- + + def _debug_setup(self) -> None: + self._agent: Optional[DebugAgent] = None + self._debug_handles: Dict[int, _Handle] = {} + self._next_handle = 1 + self._usb_state: Tuple[str, str, Tuple[AdbDevice, ...]] = ("not checked", "", ()) + self._usb_retry_at = 0.0 + + def _debug_start(self) -> None: + """Start the USB bridge. Called when the node starts.""" + self._spawn(self._usb_loop()) + + async def _debug_stop(self) -> None: + """Stop every debug operation this node runs as a computer, and close their listeners.""" + for handle in self._debug_handles.values(): + if handle.server is not None: + handle.server.close() + for task in list(handle.tasks): + task.cancel() + if handle.task is not None: + handle.task.cancel() + if handle.state == "running": + handle.state = "stopped" + + def _debug_policy(self) -> DebugPolicy: + return policy_from_settings(self._settings) + + def _debug_audit(self, level: str, text: str) -> None: + self._log(level, SOURCE_DEBUG, text) + + def _agent_instance(self) -> DebugAgent: + if self._agent is None: + identity = self.identity + providers = SystemProviders( + node_name=identity.name, + node_id=identity.node_id, + log_command=self._settings.debug_log_command, + ) + self._agent = DebugAgent(self._debug_policy, providers, self._debug_audit) + return self._agent + + def _advertised_services(self) -> List[ServiceInfo]: + """What this node offers peers: file and stream transfer, and the debug operations while debugging is on.""" + services = [ServiceInfo(name=FILE_SERVICE, description="files"), ServiceInfo(name=STREAM_SERVICE, description="streams")] + if self._settings.debug_enabled: + services += [ServiceInfo(name=wire.service_name(op), description=f"debugging: {op}") for op in wire.OPS] + return services + + def _debug_settings_changed(self, old: Settings, new: Settings) -> None: + """Called from `apply_settings`: a changed log command needs a new agent; the rest is read at each stream.""" + if old.debug_log_command != new.debug_log_command or old.debug_shell_timeout_s != new.debug_shell_timeout_s: + self._agent = None + + async def _debug_readvertise(self) -> None: + """Tell every live peer what this node now offers, after debugging was turned on or off.""" + for peer in list(self._peers.values()): + await peer.session.advertise(self._advertised_services()) + + # ----- the device side ---------------------------------------------------------------------- + + def _debug_incoming(self, request_id: int) -> None: + """A debug stream was asked for: allow it, refuse it, or leave it waiting for the user's answer.""" + pending = self._pending[request_id] + op = wire.op_of(pending.service) + decision = self._agent_instance().decide_open(op, pending.peer_id) + if decision.outcome == "refuse": + self._pending.pop(request_id, None) + self._spawn(pending.session.authorize(pending.stream, pending.service, False, decision.reason)) + self._debug_audit("warning", f"refused debug {op} from {pending.peer_id[:12]}: {decision.reason}") + elif decision.outcome == "allow": + self._spawn(self.accept_request(request_id)) + else: + self._debug_audit("info", f"{pending.peer_id[:12]} asks for debug {op}; accept or refuse it on the Debug screen") + + async def _serve_debug(self, pending) -> None: + """Run an accepted debug stream on the agent. The agent answers every outcome on the stream itself.""" + channel = OverlayChannel(pending.session, pending.stream) + await self._agent_instance().serve(wire.op_of(pending.service), pending.peer_id, channel) + + # ----- the computer side: opening streams --------------------------------------------------- + + async def _open_debug_channel(self, peer_id: str, service: str) -> Channel: + peer = self._require_ready_peer(peer_id) + if service not in [s.name for s in peer.session.services]: + raise NodeError("the device does not offer debugging; turn debugging on in its Settings (Debugging)") + try: + stream = await peer.session.open(service) + except Denied as exc: + raise NodeError("the device did not allow it: its debugging is off, this computer is not on its list, or its user refused") from exc + except NoSuchService as exc: + raise NodeError("the device does not offer this debug operation") from exc + except Unreachable as exc: + raise NodeError("the device did not answer in time; if it asked its user, the request was not accepted") from exc + except TransferdError as exc: + raise NodeError(f"could not open the debug stream: {describe(exc)}") from exc + return OverlayChannel(peer.session, stream) + + def _client(self, peer_id: str) -> DebugClient: + return DebugClient(lambda service: self._open_debug_channel(peer_id, service)) + + # ----- the computer side: operations -------------------------------------------------------- + + async def debug_info(self, peer_id: str) -> Dict[str, Any]: + try: + return await self._client(peer_id).info() + except DebugError as exc: + raise NodeError(exc.text) from exc + + async def debug_shell( + self, + peer_id: str, + command: str, + timeout: float, + on_output: Optional[Callable[[int, bytes], None]] = None, + ) -> Dict[str, Any]: + self._require_ready_peer(peer_id) + handle = self._new_handle(peer_id, "shell", command if len(command) <= 80 else command[:77] + "...") + try: + result = await self._client(peer_id).shell(command, timeout, on_output) + except (DebugError, NodeError) as exc: + # A refusal raises NodeError before any channel exists; both kinds must close the handle, or it stays "running". + text = exc.text if isinstance(exc, DebugError) else str(exc) + self._finish(handle, "failed", text) + raise NodeError(text) from exc + except asyncio.CancelledError: + self._finish(handle, "stopped") + raise + code = result.get("code") + self._finish(handle, "ended", f"{result.get('reason') or 'ended'}" + (f", exit {code}" if code is not None else "")) + return result + + async def debug_logcat_start(self, peer_id: str, text_filter: str, sink: Callable[[Dict[str, Any]], None]) -> int: + """Start streaming a device's log. Each message goes to `sink` (`line`, `drop`, or `error`). Returns the handle.""" + self._require_ready_peer(peer_id) + detail = f"lines containing '{text_filter}'" if text_filter else "all lines" + handle = self._new_handle(peer_id, "logcat", detail) + client = self._client(peer_id) + + async def run() -> None: + try: + await client.logcat(text_filter, sink) + except asyncio.CancelledError: + self._finish(handle, "stopped") + raise + except (DebugError, NodeError) as exc: + message = exc.text if isinstance(exc, DebugError) else str(exc) + self._finish(handle, "failed", message) + sink({"t": "error", "text": message}) + return + self._finish(handle, "ended") + + handle.task = self._spawn(run()) + return handle.handle + + async def debug_forward_start(self, peer_id: str, local_port: int, device_port: int) -> int: + """Listen on 127.0.0.1:`local_port` (0 chooses one) and carry each connection to `device_port` on the device.""" + self._require_ready_peer(peer_id) + handle = self._new_handle(peer_id, "forward", f"device port {device_port}") + client = self._client(peer_id) + + async def connect(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + task = asyncio.current_task() + if task is not None: + handle.tasks.add(task) + try: + try: + channel, rest = await client.forward(device_port) + except (DebugError, NodeError) as exc: + handle.note = exc.text if isinstance(exc, DebugError) else str(exc) + writer.close() + return + await bridge(reader, writer, channel, rest) + finally: + if task is not None: + handle.tasks.discard(task) + + try: + server = await asyncio.start_server(connect, "127.0.0.1", local_port) + except OSError as exc: + self._finish(handle, "failed", f"could not listen on 127.0.0.1:{local_port}: {describe(exc)}") + raise NodeError(f"could not listen on 127.0.0.1:{local_port}: {describe(exc)}") from exc + handle.server = server + port = int(server.sockets[0].getsockname()[1]) + handle.detail = f"127.0.0.1:{port} -> device port {device_port}" + self._log("info", SOURCE_DEBUG, f"forwarding 127.0.0.1:{port} to port {device_port} on {peer_id[:12]}") + return handle.handle + + async def debug_stop(self, handle_id: int) -> None: + handle = self._debug_handles.get(handle_id) + if handle is None: + raise NodeError("that debug stream is no longer known") + if handle.server is not None: + handle.server.close() + for task in list(handle.tasks): + task.cancel() + if handle.task is not None and not handle.task.done(): + handle.task.cancel() + if handle.state == "running": + self._finish(handle, "stopped") + + # ----- routes ------------------------------------------------------------------------------- + + async def attach_route(self, peer_id: str, host: str, port: int, label: str) -> None: + """Connect to `peer_id` at host:port and use that connection as a route. When there is no session with the peer + yet, this starts one; when there is, the connection becomes a second route of the same session.""" + timeout = self._settings.peer_connect_timeout + try: + reader, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout) + except (OSError, asyncio.TimeoutError) as exc: + raise NodeError(f"could not reach {label}: {describe(exc)}") from exc + try: + result = await asyncio.wait_for(handshake_initiator(reader, writer, self.identity, peer_id), timeout) + except Exception as exc: + writer.close() + raise NodeError(f"the handshake through {label} failed: {describe(exc)}") from exc + link = TcpLink(reader, writer, result.keys, kind=RouteKind.DIRECT, describe=label) + link.start() + existing = self._peers.get(result.peer_node_id) + if existing is None: + peer = self._start_peer(result.peer_node_id, [link], via="usb" if label.startswith("usb:") else "direct", relay_token=None) + await self._await_ready(peer, timeout) + else: + await self._add_route(existing, link) + + async def _add_route(self, peer, link: Link) -> None: + """Make `link` a route of a live session, and say so in the log.""" + self._observe_link(link) + peer.links.append(link) + await peer.session.add_link(link) + self._log("info", SOURCE_DEBUG, f"a {link.describe} route to {peer.node_id[:12]} was added") + + def _usb_route_up(self, peer_id: str) -> bool: + peer = self._peers.get(peer_id) + return peer is not None and any(link.describe.startswith("usb:") and link.is_up() for link in peer.links) + + async def debug_connect_wifi(self) -> None: + """Attach the Wi-Fi route to the chosen device, at the address in Settings.""" + settings = self._settings + if not settings.debug_device_id: + raise NodeError("choose the device to debug first") + if settings.debug_transport == "usb_only": + raise NodeError("the transport is set to USB only; change it in Settings to use Wi-Fi") + if not settings.debug_wifi_address.strip(): + raise NodeError("set the device's Wi-Fi address in Settings (host:port)") + host, port = parse_host_port(settings.debug_wifi_address) + await self.attach_route(settings.debug_device_id, host, port, label=f"wifi://{host}:{port}") + + async def debug_scan_usb(self) -> Tuple[AdbDevice, ...]: + """Ask adb which devices are connected. The answer is kept for the Debug screen.""" + try: + devices = tuple(await asyncio.to_thread(self._adb().devices)) + except AdbError as exc: + self._usb_state = ("unavailable", str(exc), ()) + raise NodeError(str(exc)) from exc + ready = [d for d in devices if d.ready] + if not devices: + self._usb_state = ("no device", "no device is connected over USB; plug the phone in and allow USB debugging", devices) + elif ready: + self._usb_state = ("ready", f"{len(ready)} device(s) ready over USB", devices) + else: + self._usb_state = ("needs attention", devices[0].help, devices) + return devices + + async def debug_connect_usb(self, serial: str) -> None: + """Forward the device's listener through `serial` and attach that route to the chosen device.""" + settings = self._settings + if not settings.debug_device_id: + raise NodeError("choose the device to debug first") + if settings.debug_transport == "wifi_only": + raise NodeError("the transport is set to Wi-Fi only; change it in Settings to use USB") + if settings.usb_device_port == 0: + raise NodeError("set the USB device port in Settings: the port the device's Transferd node listens on") + adb = self._adb() + local = await asyncio.to_thread(free_local_port) + try: + await asyncio.to_thread(adb.forward, serial, local, settings.usb_device_port) + except AdbError as exc: + raise NodeError(str(exc)) from exc + try: + await self.attach_route(settings.debug_device_id, "127.0.0.1", local, label=f"usb:{serial}") + except NodeError: + await self._remove_forward(adb, local) + raise + self._log("info", SOURCE_DEBUG, f"the USB route to {settings.debug_device_id[:12]} is up through {serial}") + + async def _remove_forward(self, adb: Adb, local: int) -> None: + try: + await asyncio.to_thread(adb.remove_forward, local) + except AdbError: + pass + + def _adb(self) -> Adb: + return Adb(self._settings.usb_adb_path or "adb") + + async def _usb_loop(self) -> None: + """Keep the USB route to the chosen device: when the cable is plugged in, attach it; when it is missing, the + session carries on over Wi-Fi or the relay, and the route is attached again when the cable comes back.""" + while True: + await asyncio.sleep(USB_SCAN_S) + try: + await self._usb_tick() + except Exception as exc: # the bridge must keep running whatever adb does + self._log("warning", SOURCE_DEBUG, f"the USB bridge hit an error: {describe(exc)}") + + async def _usb_tick(self) -> None: + settings = self._settings + if not settings.debug_device_id or settings.debug_transport == "wifi_only" or settings.usb_device_port == 0: + return + if self._usb_route_up(settings.debug_device_id) or time.time() < self._usb_retry_at: + return + try: + devices = await self.debug_scan_usb() + except NodeError: + self._usb_retry_at = time.time() + USB_RETRY_S + return + ready = [d for d in devices if d.ready] + if not ready: + return + try: + await self.debug_connect_usb(ready[0].serial) + except NodeError as exc: + self._log("warning", SOURCE_DEBUG, f"could not attach USB: {exc}") + self._usb_retry_at = time.time() + USB_RETRY_S + + # ----- handles and the snapshot ------------------------------------------------------------- + + def _new_handle(self, peer_id: str, kind: str, detail: str) -> _Handle: + ended = [h for h in self._debug_handles.values() if h.state != "running"] + for old in ended[: max(0, len(ended) - FINISHED_KEPT)]: + self._debug_handles.pop(old.handle, None) + handle = _Handle(self._next_handle, peer_id, kind, detail, time.time()) + self._next_handle += 1 + self._debug_handles[handle.handle] = handle + self._log("info", SOURCE_DEBUG, f"{kind} started on {peer_id[:12]}: {detail}") + return handle + + def _finish(self, handle: _Handle, state: str, note: str = "") -> None: + if handle.state != "running": + return + handle.state = state + handle.note = note + level = "error" if state == "failed" else "info" + self._log(level, SOURCE_DEBUG, f"{handle.kind} on {handle.peer_id[:12]} {state}" + (f": {note}" if note else "")) + + def debug_snapshot(self) -> DebugSnapshot: + settings = self._settings + state, detail, devices = self._usb_state + return DebugSnapshot( + agent_enabled=settings.debug_enabled, + clients=tuple(sorted(parse_clients(settings.debug_clients))), + device_id=settings.debug_device_id, + usb_state=state, + usb_detail=detail, + usb_devices=tuple(UsbDeviceSnapshot(serial=d.serial, state=d.state, model=d.model) for d in devices), + streams=tuple( + DebugStreamSnapshot(h.handle, h.peer_id, h.kind, h.detail, h.started_at, h.state, h.note) + for h in self._debug_handles.values() + ), + ) diff --git a/gui/transferd_gui/backend/errors.py b/gui/transferd_gui/backend/errors.py new file mode 100644 index 0000000..f657d74 --- /dev/null +++ b/gui/transferd_gui/backend/errors.py @@ -0,0 +1,35 @@ +"""The errors the node adapter raises, and how an exception is shown to a user. + +Kept apart from `node.py` so that the debugging part of the node can use them without importing the node. +""" + +from __future__ import annotations + +import asyncio + +from transferd.errors import Closed, Denied, NoSuchService, RateLimited, Unreachable + + +class NodeError(Exception): + """A failure with a message a user can act on. The service logs it and the views show it.""" + + +def describe(exc: BaseException) -> str: + """A short, readable reason for an exception.""" + if isinstance(exc, Unreachable): + return "the peer did not answer the open request in time (it must accept within 15 s)" + if isinstance(exc, Denied): + return "the peer refused the stream" + if isinstance(exc, NoSuchService): + return "the peer does not offer that service" + if isinstance(exc, RateLimited): + return "the peer is rate limiting that service" + if isinstance(exc, Closed): + return "the session was closed" + if isinstance(exc, asyncio.TimeoutError): + return "timed out" + if isinstance(exc, ConnectionRefusedError): + return "connection refused" + if isinstance(exc, OSError): + return exc.strerror or str(exc) + return str(exc) or type(exc).__name__ diff --git a/gui/transferd_gui/backend/mailbox_host.py b/gui/transferd_gui/backend/mailbox_host.py new file mode 100644 index 0000000..887adbc --- /dev/null +++ b/gui/transferd_gui/backend/mailbox_host.py @@ -0,0 +1,141 @@ +"""Hosting a mailbox on this computer. The server runs on the backend loop, with the settings' port. + +Off until Settings turns it on. With it on: +- a wormhole with no mailbox set in Settings meets on this computer's own mailbox; +- with `wormhole_host_network` also on, other computers can reach it. It serves wss:// with a certificate this computer made + for itself, and the fingerprint of that certificate is what the other computers pin. The share line is the address and the + fingerprint together, ready to paste into their Settings. + +Without the network setting, it listens on 127.0.0.1 only, and the address is ws://127.0.0.1, which nothing else can reach. +The status is read from the Qt thread, so it is kept under a lock; the server itself is only touched on the backend loop. +""" + +from __future__ import annotations + +import socket +import threading +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Optional, Tuple + +from transferd_gui.model.settings import Settings +from transferd_gui.wormhole import tls +from transferd_gui.wormhole.server import MailboxServer + +LOCAL_HOST = "127.0.0.1" +NETWORK_BIND = "0.0.0.0" + + +@dataclass(frozen=True) +class HostStatus: + """What the hosted mailbox is doing, for the screens to show.""" + + enabled: bool = False # Settings has hosting turned on + running: bool = False # the server is listening now + port: int = 0 # the port it listens on (or was asked to, when it could not) + network: bool = False # reachable from other computers, over wss:// with a pinned certificate + fingerprint: str = "" # the pin for the other computers; "" unless it is on the network + error: str = "" # why it is not running, in words a user can act on + + def share_line(self, host: str) -> str: + """The address another computer adds to its mailbox list, given this computer's network `host`.""" + if not (self.running and self.network and host): + return "" + return f"wss://{host}:{self.port}#{self.fingerprint}" + + +def network_host() -> str: + """This computer's address on the local network, as other computers would reach it. Empty when it cannot be found.""" + try: + # Connecting a UDP socket sends nothing; it only makes the system pick the interface it would use. + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe: + probe.connect(("10.255.255.255", 1)) + address = probe.getsockname()[0] + if address and not address.startswith("127."): + return address + except OSError: + pass + try: + return socket.gethostname() + except OSError: + return "" + + +class MailboxHost: + """Starts, stops and reports the mailbox this computer hosts. One instance per app.""" + + def __init__(self, folder: Path, *, network_bind: str = NETWORK_BIND) -> None: + self._folder = folder + self._network_bind = network_bind + self._lock = threading.Lock() + self._server: Optional[MailboxServer] = None + self._config: Optional[Tuple[int, bool]] = None + self._status = HostStatus() + + # ----- the backend loop ---------------------------------------------------------------------------- + + async def apply(self, settings: Settings) -> None: + """Make the hosting match the settings: stop it, start it, or restart it when the port or the network changed.""" + if not settings.wormhole_host: + await self.stop() + self._set(HostStatus()) + return + wanted = (settings.wormhole_host_port, settings.wormhole_host_network) + if self._server is not None and self._config == wanted: + return + await self.stop() + await self._start(*wanted) + + async def stop(self) -> None: + server, self._server = self._server, None + self._config = None + if server is not None: + await server.close() + with self._lock: + self._status = replace(self._status, running=False) + + async def _start(self, port: int, network: bool) -> None: + self._set(HostStatus(enabled=True, port=port, network=network)) + fingerprint = "" + context = None + if network: + try: + identity = tls.load_or_create(self._folder) + context = tls.server_context(identity) + fingerprint = identity.fingerprint + except Exception as exc: # a folder that cannot be written, or a certificate that cannot be read or made + self._set(HostStatus(enabled=True, port=port, network=True, error=f"could not make the mailbox's certificate: {exc}")) + return + server = MailboxServer() + try: + bound = await server.start(self._network_bind if network else LOCAL_HOST, port, tls=context) + except OSError as exc: + reason = exc.strerror or str(exc) + self._set(HostStatus(enabled=True, port=port, network=network, error=f"could not listen on port {port}: {reason}")) + return + self._server = server + self._config = (port, network) + self._set(HostStatus(enabled=True, running=True, port=bound, network=network, fingerprint=fingerprint)) + + # ----- reading (any thread) -------------------------------------------------------------------------- + + def status(self) -> HostStatus: + with self._lock: + return self._status + + def address_here(self) -> str: + """The address this computer's own wormholes meet on when no mailbox is set. Empty when nothing is hosted.""" + status = self.status() + if not status.running: + return "" + if status.network: + return f"wss://{LOCAL_HOST}:{status.port}#{status.fingerprint}" + return f"ws://{LOCAL_HOST}:{status.port}" + + def share_line(self) -> str: + """The line another computer pastes into its mailbox list. Empty unless the mailbox is on the network.""" + return self.status().share_line(network_host()) + + def _set(self, status: HostStatus) -> None: + with self._lock: + self._status = status diff --git a/gui/transferd_gui/backend/node.py b/gui/transferd_gui/backend/node.py index 3086a3f..51140d5 100644 --- a/gui/transferd_gui/backend/node.py +++ b/gui/transferd_gui/backend/node.py @@ -21,8 +21,7 @@ from pathlib import Path from typing import Callable, Deque, Dict, List, Optional, Set -from transferd.errors import Closed, Denied, InviteError, NoSuchService, RateLimited, TransferdError, Unreachable -from transferd.frames import ServiceInfo +from transferd.errors import InviteError, TransferdError from transferd.handshake import handshake_initiator, handshake_responder from transferd.identity import HybridIdentity, key_fingerprint, relay_token_for from transferd.invite import MadeInvite, accept_invite, make_invite @@ -31,14 +30,16 @@ from transferd.punch import addr_text from transferd.relay_hub import REREGISTER_EVERY, RelayHub +from transferd_gui.backend.debugnode import DebugNodeMixin +from transferd_gui.backend.errors import NodeError, describe from transferd_gui.backend.files import ( CHUNK, FILE_SERVICE, - STREAM_SERVICE, HeaderReader, encode_header, unique_path, ) +from transferd_gui.debug import wire from transferd_gui.backend.observe import count_probe_answers, count_received, count_sent, observe_async from transferd_gui.model.settings import NODE_NAME_MAX, Settings, parse_host_port from transferd_gui.model.snapshot import ( @@ -72,31 +73,6 @@ Publish = Callable[[NodeSnapshot], None] -class NodeError(Exception): - """A failure with a message a user can act on. The service logs it and the views show it.""" - - -def describe(exc: BaseException) -> str: - """A short, readable reason for an exception.""" - if isinstance(exc, Unreachable): - return "the peer did not answer the open request in time (it must accept within 15 s)" - if isinstance(exc, Denied): - return "the peer refused the stream" - if isinstance(exc, NoSuchService): - return "the peer does not offer that service" - if isinstance(exc, RateLimited): - return "the peer is rate limiting that service" - if isinstance(exc, Closed): - return "the session was closed" - if isinstance(exc, asyncio.TimeoutError): - return "timed out" - if isinstance(exc, ConnectionRefusedError): - return "connection refused" - if isinstance(exc, OSError): - return exc.strerror or str(exc) - return str(exc) or type(exc).__name__ - - @dataclass class _Peer: node_id: str @@ -130,7 +106,7 @@ class _RelayRecord: failures: int = 0 -class Node: +class Node(DebugNodeMixin): """One Transferd node in the GUI: its identity, its listener, its relay registration and its peers.""" def __init__(self, settings: Settings, log: Log, publish: Optional[Publish] = None) -> None: @@ -153,6 +129,7 @@ def __init__(self, settings: Settings, log: Log, publish: Optional[Publish] = No self._transfers: Deque[TransferRecord] = deque(maxlen=HISTORY) self._locate: Optional[LocateResult] = None self._tasks: Set[asyncio.Task] = set() + self._debug_setup() # ----- identity ----------------------------------------------------------------------------- @@ -194,6 +171,7 @@ async def start(self) -> None: self._identity = self._load_identity() self._log("info", SOURCE_NODE, f"node {self.identity.node_id[:12]} started as '{self.identity.name}'") self._spawn(self._tick()) + self._debug_start() if self._settings.allow_incoming: await self._open_listener() if self._settings.relay_address: @@ -204,6 +182,7 @@ async def start(self) -> None: async def stop(self) -> None: """Close relay registration, sessions, listener and the ticker. Every waiting call is released.""" + await self._debug_stop() await self.disconnect_relay() for peer in list(self._peers.values()): await peer.session.shutdown() @@ -217,6 +196,10 @@ async def apply_settings(self, settings: Settings) -> None: """Take new settings. Changing whether incoming is allowed opens or closes the listener, and changing the relay address drops the current registration (the user connects again).""" old, self._settings = self._settings, settings + self._debug_settings_changed(old, settings) + if self._identity is not None and old.debug_enabled != settings.debug_enabled: + await self._debug_readvertise() + self._log("info", SOURCE_NODE, "debugging is " + ("on: this node answers debug requests from the computers on its list" if settings.debug_enabled else "off")) if self._identity is not None and settings.node_name != old.node_name: self._log("info", SOURCE_NODE, "the node name takes effect after a restart") if settings.relay_address != old.relay_address and self._hub is not None: @@ -277,12 +260,14 @@ async def _serve_direct(self, reader: asyncio.StreamReader, writer: asyncio.Stre self._log("warning", SOURCE_PEER, f"refused a connection from {where_text}: {describe(exc)}") writer.close() return - if result.peer_node_id in self._peers: - self._log("warning", SOURCE_PEER, f"{where_text} is already connected as {result.peer_node_id[:12]}; closed the new connection") - writer.close() - return link = TcpLink(reader, writer, result.keys, kind=RouteKind.DIRECT, describe=f"tcp://{where_text}") link.start() + existing = self._peers.get(result.peer_node_id) + if existing is not None: + # A second route to a peer we already have a session with (for example the same device over USB and Wi-Fi): + # it becomes one more route of that session, not a refused connection. + await self._add_route(existing, link) + return self._start_peer(result.peer_node_id, [link], via="direct", relay_token=None) # ----- relay -------------------------------------------------------------------------------- @@ -492,8 +477,7 @@ def _start_peer(self, peer_id: str, links: List[Link], via: str, relay_token: Op for link in links: self._observe_link(link) events: asyncio.Queue = asyncio.Queue() - services = [ServiceInfo(name=FILE_SERVICE, description="files"), ServiceInfo(name=STREAM_SERVICE, description="streams")] - setup = SessionSetup(peer_node_id=peer_id, peer_name="", identity=self.identity, services=services) + setup = SessionSetup(peer_node_id=peer_id, peer_name="", identity=self.identity, services=self._advertised_services()) session = spawn(setup, links, events) peer = _Peer( node_id=peer_id, @@ -549,6 +533,9 @@ def _new_request(self, peer: _Peer, stream: int, service: str) -> None: request_id = self._next_request self._next_request += 1 self._pending[request_id] = _Pending(request_id, peer.node_id, peer.session, stream, service, time.time()) + if wire.op_of(service) is not None: + self._debug_incoming(request_id) + return if service == FILE_SERVICE and self._settings.auto_accept_files: self._log("info", SOURCE_PEER, f"{peer.node_id[:12]} sends a file; accepting it (auto-accept is on)") self._spawn(self.accept_request(request_id)) @@ -591,6 +578,9 @@ async def accept_request(self, request_id: int) -> None: if pending is None: raise NodeError("that request is no longer waiting") await pending.session.authorize(pending.stream, pending.service, True) + if wire.op_of(pending.service) is not None: + self._spawn(self._serve_debug(pending)) + return if pending.service == FILE_SERVICE: self._spawn(self._receive_file(pending)) else: @@ -601,6 +591,9 @@ async def refuse_request(self, request_id: int) -> None: if pending is None: raise NodeError("that request is no longer waiting") await pending.session.authorize(pending.stream, pending.service, False, "refused by the user") + if wire.op_of(pending.service) is not None: + self._debug_audit("info", f"refused debug {wire.op_of(pending.service)} from {pending.peer_id[:12]} (by the user)") + return self._log("info", SOURCE_TRANSFER, f"refused '{pending.service}' from {pending.peer_id[:12]}") def _limit_bytes(self) -> int: @@ -772,6 +765,7 @@ def snapshot(self) -> NodeSnapshot: ), transfers=tuple(self._transfers), locate=self._locate, + debug=self.debug_snapshot(), ) def _peer_name(self, peer_id: str) -> str: @@ -845,6 +839,7 @@ def _route_snapshot(self, peer: _Peer, link: Link, report) -> RouteSnapshot: kind=link.kind.value, up=link.is_up(), closed=link.is_closed(), + label=link.describe, rtt_ms=metrics.rtt_ms if measured else None, srtt_ms=report.srtt_ms if report is not None and report.srtt_ms > 0.0 else None, loss=metrics.loss if measured else None, diff --git a/gui/transferd_gui/backend/service.py b/gui/transferd_gui/backend/service.py index c8c67ed..79cf245 100644 --- a/gui/transferd_gui/backend/service.py +++ b/gui/transferd_gui/backend/service.py @@ -13,6 +13,7 @@ from typing import Any, Callable, Coroutine, Mapping, Optional, Tuple from transferd_gui.backend.ghost import GhostService +from transferd_gui.backend.mailbox_host import MailboxHost from transferd_gui.backend.node import Node, NodeError, describe from transferd_gui.backend.worker import BackendWorker from transferd_gui.model.eventlog import EventLogStore, LogEntry @@ -24,6 +25,14 @@ OnDone = Callable[[bool, Any], None] +def _hosting_changed(old: Settings, new: Settings) -> bool: + return (old.wormhole_host, old.wormhole_host_port, old.wormhole_host_network) != ( + new.wormhole_host, + new.wormhole_host_port, + new.wormhole_host_network, + ) + + class TransferdService: """Owns the backend thread, the node, the settings file and the event log.""" @@ -44,6 +53,7 @@ def __init__( self._lock = threading.Lock() self._worker = BackendWorker() self._node = Node(self._settings, self._log, self._publish) + self._mailbox_host = MailboxHost(Path(self._settings.data_dir) / "wormhole") # ----- settings ----------------------------------------------------------------------------- @@ -79,20 +89,44 @@ def change_settings(self, changes: Mapping[str, Any]) -> Settings: self._log("info", "settings", "the data directory takes effect after a restart") if self._worker.running: self.run(self._node.apply_settings(new), "apply settings") + if _hosting_changed(old, new): + self.run(self._apply_hosting(new), "host a mailbox") return new def ghost(self) -> GhostService: return GhostService(Path(self._settings.data_dir)) + @property + def mailbox_host(self) -> MailboxHost: + """This computer's hosted mailbox. Its status can be read from any thread.""" + return self._mailbox_host + + async def _apply_hosting(self, settings: Settings) -> None: + await self._mailbox_host.apply(settings) + status = self._mailbox_host.status() + if status.error: + self._log("error", "mailbox", status.error) + elif status.running: + where = "on the network, with a pinned certificate" if status.network else "on this computer only" + self._log("info", "mailbox", f"hosting a mailbox on port {status.port}, {where}") + elif not settings.wormhole_host: + self._log("info", "mailbox", "stopped hosting the mailbox") + # ----- lifecycle ---------------------------------------------------------------------------- def start(self) -> None: self._worker.start() self.run(self._node.start(), "start the node") + if self._settings.wormhole_host: + self.run(self._apply_hosting(self._settings), "host a mailbox") def stop(self, timeout: float = 5.0) -> None: if not self._worker.running: return + try: + self._worker.submit(self._mailbox_host.stop()).result(timeout=timeout) + except Exception as exc: # the hosted mailbox must not keep the app from closing + self._log("warning", "mailbox", f"stopping the hosted mailbox was not clean: {describe(exc)}") try: self._worker.submit(self._node.stop()).result(timeout=timeout) except Exception as exc: # stopping must finish even when a session will not close cleanly diff --git a/gui/transferd_gui/backend/wormhole.py b/gui/transferd_gui/backend/wormhole.py new file mode 100644 index 0000000..04a4950 --- /dev/null +++ b/gui/transferd_gui/backend/wormhole.py @@ -0,0 +1,112 @@ +"""The wormhole as the app runs it: what is offered, the settings it uses, and the calls the screen makes. + +Every method here is a coroutine. The screen runs them through the service (`TransferdService.run`) so they execute on the +backend loop, the same as the node's actions. Nothing here touches Qt. + +Where a wormhole meets: the mailbox list in Settings (`wormhole_mailbox`), tried in order. When no list is set, a wormhole +meets on this computer's own hosted mailbox, if hosting is on (`backend.mailbox_host`). The relay and the download folder come +from Settings too. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Callable, Optional, Union + +from transferd_gui.backend.service import TransferdService +from transferd_gui.model.settings import Settings +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.codes import parse as parse_code +from transferd_gui.wormhole.endpoint import OverlayTransit +from transferd_gui.wormhole.errors import WormholeError +from transferd_gui.wormhole.session import ReceiveResult, Receiver, SendResult, Sender +from transferd_gui.wormhole.transfer import prepare_file, prepare_folder, remove_quietly + +OnState = Callable[[str], None] +NO_MAILBOX = "Set a mailbox in Settings (Wormhole), or host one on this computer, before using a wormhole." + + +def mailbox_problem(settings: Settings, hosted: str = "") -> str: + """Why a wormhole cannot start, or the empty string when it can. `hosted` is this computer's own mailbox address, or "".""" + if not settings.wormhole_mailbox.strip() and not hosted: + return NO_MAILBOX + return "" + + +class WormholeService: + """Builds and runs one wormhole attempt at a time, from the settings the app holds.""" + + def __init__(self, service: TransferdService) -> None: + self._service = service + + def _settings(self) -> Settings: + return self._service.settings + + def scratch_dir(self) -> Path: + """Where a folder is zipped before it is offered, and where a received folder is staged. Removed after use.""" + path = Path(self._settings().data_dir) / "wormhole" + path.mkdir(parents=True, exist_ok=True) + return path + + def mailbox(self) -> str: + """The mailbox list a wormhole meets on: the one in Settings, or this computer's own when Settings names none.""" + return self._settings().wormhole_mailbox.strip() or self._service.mailbox_host.address_here() + + def problem(self) -> str: + """Why a wormhole cannot start now, or the empty string.""" + return mailbox_problem(self._settings(), self._service.mailbox_host.address_here()) + + def _transit(self, on_state: Optional[OnState]) -> OverlayTransit: + settings = self._settings() + return OverlayTransit( + name=settings.node_name or "Transferd", + relay=settings.relay_address, + streams=settings.wormhole_streams, + on_state=on_state, + ) + + async def start_send(self, kind: str, value: str, on_state: Optional[OnState] = None) -> Sender: + """Prepare what is offered and reserve a code. Returns the sender, whose `code` the screen shows.""" + problem = self.problem() + if problem: + raise WormholeError(problem) + if kind == "text": + offer, source = P.Offer.for_text(value), None + elif kind == "file": + offer, source = prepare_file(Path(value)) + elif kind == "folder": + offer, source = prepare_folder(Path(value), self.scratch_dir()) + else: + raise WormholeError("send a file, a folder or a text") + sender = Sender(self.mailbox(), transit=self._transit(on_state), offer=offer, source=source, on_state=on_state) + await sender.start() + return sender + + async def run_send(self, sender: Sender) -> SendResult: + """Carry the sender through to the end. A folder's archive is removed whatever the outcome.""" + try: + return await sender.run() + finally: + if sender.offer.kind == "directory" and sender.source is not None: + remove_quietly(sender.source) + + async def open_receive(self, code_text: str, on_state: Optional[OnState] = None) -> Receiver: + """Read the code, join the mailbox, and read what is offered. The screen then asks the user to accept or decline.""" + problem = self.problem() + if problem: + raise WormholeError(problem) + code = parse_code(code_text) + receiver = Receiver(self.mailbox(), code, transit=self._transit(on_state), on_state=on_state) + await receiver.connect() + await receiver.offer() + return receiver + + async def finish_receive(self, receiver: Receiver, accept: bool, reason: str = "") -> ReceiveResult: + """Answer the offer and, when accepted, receive it into the download folder.""" + await receiver.answer(accept, reason) + folder = Path(self._settings().download_dir) + return await receiver.finish(folder) + + async def abandon(self, exchange: Union[Sender, Receiver]) -> None: + """Stop an attempt that is waiting on the user: a sender's code stops working, a receiver declines its offer.""" + await exchange.abandon() diff --git a/gui/transferd_gui/debug/agent.py b/gui/transferd_gui/debug/agent.py new file mode 100644 index 0000000..6af7e58 --- /dev/null +++ b/gui/transferd_gui/debug/agent.py @@ -0,0 +1,386 @@ +"""The device side of the debug protocol: answers `info`, `logcat`, `shell` and `forward` streams under the device's policy. + +The agent does not decide who is asked about; the node does, when a stream opens (`decide_open`). Once a stream is +accepted, `serve` reads the request, checks it against the policy again, and runs the operation. Everything it does is +reported through `audit`, so the device's event log shows every stream and how it ended. + +What the device can read, run and reach comes from a `Providers` object. `providers.SystemProviders` is the real one; +tests give their own. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, AsyncIterator, Callable, Dict, Optional, Protocol, Tuple + +from transferd_gui.debug.policy import Decision, DebugPolicy, decide +from transferd_gui.debug.stream import Channel, ChannelReset +from transferd_gui.debug.wire import ( + MAX_REQUEST, + MAX_SHELL_COMMAND, + MAX_SHELL_TIMEOUT_S, + PROTOCOL_VERSION, + LineDecoder, + WireError, + b64, + clip_text, + encode, +) + +#: Bytes per shell output message. +OUTPUT_CHUNK = 16 * 1024 +#: Bytes read from a forwarded connection at a time. +FORWARD_CHUNK = 64 * 1024 +#: Log lines held while the client reads more slowly than the log produces them. +LOG_QUEUE = 1024 +#: The longest log filter text a client may send. +MAX_FILTER = 256 +#: How often a logcat stream reports the lines it dropped. +DROP_REPORT_S = 0.5 + +Audit = Callable[[str, str], None] + + +class ShellRun(Protocol): + """A running shell command: its output as (fd, bytes), its exit code, and a way to stop it.""" + + def output(self) -> AsyncIterator[Tuple[int, bytes]]: ... + + async def wait(self) -> Optional[int]: ... + + def kill(self) -> None: ... + + async def close(self) -> None: + """Stop the command if it is still running, and wait until it has gone.""" + + +class Providers(Protocol): + """What the device gives the agent. Each method can be replaced in tests.""" + + def info(self) -> Dict[str, Any]: + """Device properties for the `info` operation.""" + + def log_lines(self, text_filter: str) -> Optional[AsyncIterator[str]]: + """Log lines that contain `text_filter`, or None when the device has no log source configured.""" + + def run_shell(self, command: str) -> ShellRun: + """Start a shell command. Nothing runs until its `output` is iterated.""" + + async def open_port(self, port: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: + """Connect to a port on this device's loopback. Raises OSError when nothing listens there.""" + + +class _Refused(Exception): + """The request cannot be served. The agent answers with this code and text before the operation starts.""" + + def __init__(self, code: str, text: str) -> None: + super().__init__(text) + self.code = code + self.text = text + + +def _quiet(_level: str, _text: str) -> None: + return None + + +class DebugAgent: + """Serves debug streams under the policy `policy()` returns now (the user may change it while the agent runs).""" + + def __init__( + self, + policy: Callable[[], DebugPolicy], + providers: Providers, + audit: Audit = _quiet, + ) -> None: + self._policy = policy + self._providers = providers + self._audit = audit + self._active: Dict[str, int] = {} + + def decide_open(self, op: str, client_node_id: str) -> Decision: + """Allow, ask or refuse a stream the client has just opened, under the policy now in force.""" + return decide(self._policy(), op, client_node_id) + + def active_streams(self, client_node_id: str) -> int: + return self._active.get(client_node_id, 0) + + async def serve(self, op: str, client_node_id: str, channel: Channel) -> None: + """Run one accepted stream to its end, then release it. Never raises: every failure is answered on the stream and audited.""" + try: + await self._serve(op, client_node_id, channel) + finally: + try: + await channel.close() + except Exception: + pass # released already, or the session is gone + + async def _serve(self, op: str, client_node_id: str, channel: Channel) -> None: + who = _short(client_node_id) + policy = self._policy() + decision = decide(policy, op, client_node_id) + if decision.outcome == "refuse": + await self._answer_error(channel, decision.code, decision.reason) + self._audit("warning", f"debug {op} from {who} refused: {decision.reason}") + return + if self._active.get(client_node_id, 0) >= policy.streams_per_client: + await self._answer_error(channel, "too_many", "this computer already has the most debug streams open") + self._audit("warning", f"debug {op} from {who} refused: too many open streams") + return + self._active[client_node_id] = self._active.get(client_node_id, 0) + 1 + try: + await self._serve_open(op, who, client_node_id, channel, policy) + except ChannelReset: + self._audit("info", f"debug {op} from {who} ended: the computer left the stream") + except Exception as exc: # the operation failed in a way the agent did not expect; the stream says so + self._audit("error", f"debug {op} from {who} failed: {exc}") + await _reset_quietly(channel, "the device failed the operation") + finally: + count = self._active.get(client_node_id, 1) - 1 + if count > 0: + self._active[client_node_id] = count + else: + self._active.pop(client_node_id, None) + + async def _serve_open(self, op: str, who: str, client_id: str, channel: Channel, policy: DebugPolicy) -> None: + decoder = LineDecoder(MAX_REQUEST) + try: + args = await _read_request(channel, decoder) + except _Refused as refused: + await self._answer_error(channel, refused.code, refused.text) + self._audit("warning", f"debug {op} from {who} refused: {refused.text}") + return + try: + if op == "info": + await self._info(channel) + elif op == "logcat": + await self._logcat(channel, args, who) + elif op == "shell": + await self._shell(channel, args, who, policy) + elif op == "forward": + await self._forward(channel, args, decoder, who, policy) + else: + raise _Refused("bad_request", f"there is no operation '{op}'") + except _Refused as refused: + await self._answer_error(channel, refused.code, refused.text) + self._audit("warning", f"debug {op} from {who} refused: {refused.text}") + + # ----- operations --------------------------------------------------------------------------- + + async def _info(self, channel: Channel) -> None: + await channel.write(encode({"t": "ok"})) + await channel.write(encode({"t": "info", "props": self._providers.info()}, _LIMIT)) + await channel.end() + self._audit("info", "debug info answered") + + async def _logcat(self, channel: Channel, args: Dict[str, Any], who: str) -> None: + text_filter = _text_arg(args, "filter", "", MAX_FILTER) + lines = self._providers.log_lines(text_filter) + if lines is None: + raise _Refused("unavailable", "this device has no log source configured") + await channel.write(encode({"t": "ok"})) + self._audit("info", f"debug logcat from {who} started" + (f" (filter '{text_filter}')" if text_filter else "")) + + queue: asyncio.Queue = asyncio.Queue(maxsize=LOG_QUEUE) + counts = {"dropped": 0, "reported": 0} + stop = asyncio.Event() + + async def produce() -> None: + try: + async for line in lines: + try: + queue.put_nowait(line) + except asyncio.QueueFull: + counts["dropped"] += 1 + finally: + stop.set() + + async def watch() -> None: + # The client sends nothing after its request; its end (or a reset) is the only thing to watch for. + try: + while await channel.read() is not None: + pass + except ChannelReset: + pass + stop.set() + + producer = asyncio.create_task(produce()) + watcher = asyncio.create_task(watch()) + try: + while True: + if counts["dropped"] > counts["reported"]: + count = counts["dropped"] - counts["reported"] + counts["reported"] = counts["dropped"] + await channel.write(encode({"t": "drop", "count": count})) + if stop.is_set() and queue.empty(): + break + try: + line = await asyncio.wait_for(queue.get(), DROP_REPORT_S) + except asyncio.TimeoutError: + continue + text, cut = clip_text(line) + await channel.write(encode({"t": "line", "text": text, "cut": cut}, _LIMIT)) + finally: + for task in (producer, watcher): + task.cancel() + await asyncio.gather(producer, watcher, return_exceptions=True) + aclose = getattr(lines, "aclose", None) + if aclose is not None: + await aclose() + await channel.end() + self._audit("info", f"debug logcat from {who} ended") + + async def _shell(self, channel: Channel, args: Dict[str, Any], who: str, policy: DebugPolicy) -> None: + command = _text_arg(args, "command", "", MAX_SHELL_COMMAND) + if not command.strip(): + raise _Refused("bad_request", "the shell command is empty") + limit = min(policy.shell_timeout_s, MAX_SHELL_TIMEOUT_S) + requested = args.get("timeout", limit) + if isinstance(requested, bool) or not isinstance(requested, (int, float)) or requested <= 0: + raise _Refused("bad_request", "the shell timeout must be a positive number of seconds") + timeout = min(float(requested), limit) + run = self._providers.run_shell(command) + await channel.write(encode({"t": "ok"})) + self._audit("warning", f"debug shell from {who} started: {command[:200]}") + + reason = "exited" + sent = 0 + + async def pump() -> None: + nonlocal reason, sent + output = run.output() + try: + async for fd, data in output: + for start in range(0, len(data), OUTPUT_CHUNK): + piece = data[start : start + OUTPUT_CHUNK] + if sent + len(piece) > policy.shell_output_limit: + reason = "output_limit" + run.kill() + return + sent += len(piece) + await channel.write(encode({"t": "out", "fd": fd, "b64": b64(piece)}, _LIMIT)) + finally: + aclose = getattr(output, "aclose", None) + if aclose is not None: + await aclose() + + async def watch() -> None: + try: + while await channel.read() is not None: + pass + except ChannelReset: + pass + run.kill() + + watcher = asyncio.create_task(watch()) + code: Optional[int] = None + try: + await asyncio.wait_for(pump(), timeout) + code = await run.wait() + except asyncio.TimeoutError: + reason = "timeout" + finally: + # Whatever ended the run (timeout, limit, the computer leaving, a failure), nothing is left running. + await run.close() + watcher.cancel() + await asyncio.gather(watcher, return_exceptions=True) + await channel.write(encode({"t": "exit", "code": code, "reason": reason})) + await channel.end() + self._audit("warning", f"debug shell from {who} ended: {reason}" + (f", exit {code}" if code is not None else "")) + + async def _forward(self, channel: Channel, args: Dict[str, Any], decoder: LineDecoder, who: str, policy: DebugPolicy) -> None: + port = args.get("port") + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise _Refused("bad_request", "the forward port must be a number from 1 to 65535") + if port not in policy.forward_ports: + raise _Refused("not_allowed", f"port {port} is not on this device's forward list") + try: + reader, writer = await self._providers.open_port(port) + except OSError as exc: + raise _Refused("failed", f"nothing is listening on port {port} on this device ({exc.strerror or exc})") from exc + await channel.write(encode({"t": "ok"})) + self._audit("warning", f"debug forward from {who} to port {port} started") + pending = decoder.rest() + if pending: + writer.write(pending) + + async def to_device() -> None: + try: + while True: + data = await channel.read() + if data is None: + break + writer.write(data) + await writer.drain() + except (ChannelReset, ConnectionError): + writer.transport.abort() + return + if writer.can_write_eof(): + writer.write_eof() + + async def to_client() -> None: + while True: + data = await reader.read(FORWARD_CHUNK) + if not data: + break + await channel.write(data) + await channel.end() + + try: + await asyncio.gather(to_device(), to_client()) + finally: + writer.close() + await asyncio.gather(writer.wait_closed(), return_exceptions=True) + self._audit("warning", f"debug forward from {who} to port {port} ended") + + # ----- answers ------------------------------------------------------------------------------ + + async def _answer_error(self, channel: Channel, code: str, text: str) -> None: + try: + await channel.write(encode({"t": "error", "code": code, "text": text})) + await channel.end() + except ChannelReset: + pass + + +def _text_arg(args: Dict[str, Any], key: str, default: str, limit: int) -> str: + value = args.get(key, default) + if not isinstance(value, str): + raise _Refused("bad_request", f"'{key}' must be text") + if len(value) > limit: + raise _Refused("bad_request", f"'{key}' is longer than {limit} characters") + return value + + +async def _read_request(channel: Channel, decoder: LineDecoder) -> Dict[str, Any]: + """The request line, and its `args`. Bytes after the line stay in `decoder` for a raw stream.""" + while True: + try: + message = decoder.take() + except WireError as exc: + raise _Refused("bad_request", str(exc)) from exc + if message is not None: + break + chunk = await channel.read() + if chunk is None: + raise _Refused("bad_request", "the stream ended before the request") + decoder.push(chunk) + if message.get("v") != PROTOCOL_VERSION: + raise _Refused("unsupported_version", f"this device speaks debug protocol version {PROTOCOL_VERSION}") + args = message.get("args", {}) + if not isinstance(args, dict): + raise _Refused("bad_request", "'args' must be an object") + return args + + +async def _reset_quietly(channel: Channel, reason: str) -> None: + try: + await channel.reset(reason) + except ChannelReset: + pass + + +def _short(node_id: str) -> str: + return node_id[:12] + + +_LIMIT = 64 * 1024 diff --git a/gui/transferd_gui/debug/client.py b/gui/transferd_gui/debug/client.py new file mode 100644 index 0000000..8734fb0 --- /dev/null +++ b/gui/transferd_gui/debug/client.py @@ -0,0 +1,202 @@ +"""The debugging computer's side: `info`, `logcat`, `shell` and `forward` against a device, over channels. + +`open_channel(service)` is how a client gets a channel: the node opens the overlay stream for `service` and returns a +channel once the device has accepted it. A refusal raises `DebugError`, with the device's code and text, so the +caller can say what happened in plain words. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, Awaitable, Callable, Dict, Optional, Tuple + +from transferd_gui.debug.stream import Channel, ChannelReset +from transferd_gui.debug.wire import LineDecoder, WireError, request, service_name, unb64 + +OpenChannel = Callable[[str], Awaitable[Channel]] +#: Called with each message the device sends for a logcat stream: `line` or `drop`. +OnLog = Callable[[Dict[str, Any]], None] +#: Called with each shell output piece as (fd, bytes). +OnOutput = Callable[[int, bytes], None] +READ_SIZE = 64 * 1024 + + +class DebugError(Exception): + """The device refused the operation, failed it, or broke the protocol. `code` is one of the protocol's error codes.""" + + def __init__(self, code: str, text: str) -> None: + super().__init__(text) + self.code = code + self.text = text + + +class DebugClient: + """The operations a debugging computer runs against one device.""" + + def __init__(self, open_channel: OpenChannel) -> None: + self._open_channel = open_channel + + async def info(self) -> Dict[str, Any]: + channel = await self._start("info", {}) + try: + decoder = LineDecoder() + await _expect_ok(channel, decoder) + while True: + message = await _next(channel, decoder) + if message is None: + raise DebugError("failed", "the device ended the stream before its information") + if message.get("t") == "info": + props = message.get("props") + return dict(props) if isinstance(props, dict) else {} + if message.get("t") == "error": + raise _device_error(message) + finally: + await channel.close() + + async def logcat(self, text_filter: str, on_log: OnLog) -> None: + """Stream log lines until the device ends the stream. Cancel the task to stop: the stream is ended on the device.""" + channel = await self._start("logcat", {"filter": text_filter} if text_filter else {}) + decoder = LineDecoder() + try: + await _expect_ok(channel, decoder) + while True: + message = await _next(channel, decoder) + if message is None: + return + kind = message.get("t") + if kind in ("line", "drop"): + on_log(message) + elif kind == "error": + raise _device_error(message) + finally: + await channel.close() + + async def shell(self, command: str, timeout: float, on_output: Optional[OnOutput] = None) -> Dict[str, Any]: + """Run a command on the device. Returns its exit code, why it ended, and what it printed (stdout and stderr).""" + channel = await self._start("shell", {"command": command, "timeout": timeout}) + decoder = LineDecoder() + out = {1: bytearray(), 2: bytearray()} + result: Dict[str, Any] = {"code": None, "reason": ""} + try: + await _expect_ok(channel, decoder) + while True: + message = await _next(channel, decoder) + if message is None: + raise DebugError("failed", "the device ended the stream before the command finished") + kind = message.get("t") + if kind == "out": + fd = message.get("fd") + data = unb64(str(message.get("b64", ""))) + if fd in out: + out[fd] += data + if on_output is not None: + on_output(fd if fd in out else 1, data) + elif kind == "exit": + code = message.get("code") + result["code"] = code if isinstance(code, int) else None + result["reason"] = str(message.get("reason", "")) + break + elif kind == "error": + raise _device_error(message) + finally: + await channel.close() + result["stdout"] = bytes(out[1]) + result["stderr"] = bytes(out[2]) + return result + + async def forward(self, port: int) -> Tuple[Channel, bytes]: + """Open a raw connection to `port` on the device's loopback. Returns the channel, which carries bytes both ways, + and any bytes the device sent in the same read as its answer: they belong to the connection.""" + channel = await self._start("forward", {"port": port}) + decoder = LineDecoder() + try: + await _expect_ok(channel, decoder) + except BaseException: + await channel.reset("the forward did not start") + raise + return channel, decoder.rest() + + async def _start(self, op: str, args: Dict[str, Any]) -> Channel: + channel = await self._open_channel(service_name(op)) + try: + await channel.write(request(args)) + except BaseException: + await channel.reset("could not send the request") + raise + return channel + + +async def bridge(local_reader: asyncio.StreamReader, local_writer: asyncio.StreamWriter, channel: Channel, rest: bytes = b"") -> None: + """Carry bytes between a local TCP connection and a forward channel until both have ended.""" + + async def up() -> None: + try: + if rest: + local_writer.write(rest) + await local_writer.drain() + while True: + data = await local_reader.read(READ_SIZE) + if not data: + break + await channel.write(data) + except (ChannelReset, ConnectionError): + await channel.reset("the local connection failed") + return + await channel.end() + + async def down() -> None: + try: + while True: + data = await channel.read() + if data is None: + break + local_writer.write(data) + await local_writer.drain() + except (ChannelReset, ConnectionError): + local_writer.transport.abort() + return + if local_writer.can_write_eof(): + local_writer.write_eof() + + try: + await asyncio.gather(up(), down()) + finally: + await channel.close() + local_writer.close() + await asyncio.gather(local_writer.wait_closed(), return_exceptions=True) + + +async def _next(channel: Channel, decoder: LineDecoder) -> Optional[Dict[str, Any]]: + """The next message from the device, or None when the stream has ended.""" + while True: + try: + message = decoder.take() + except WireError as exc: + raise DebugError("bad_request", f"the device sent something that is not the protocol: {exc}") from exc + if message is not None: + return message + try: + chunk = await channel.read() + except ChannelReset as exc: + raise DebugError("failed", f"the device reset the stream: {exc}") from exc + if chunk is None: + return None + decoder.push(chunk) + + +async def _expect_ok(channel: Channel, decoder: LineDecoder) -> None: + """The device's first message must be `ok`. Anything else is its refusal, or a protocol break.""" + message = await _next(channel, decoder) + if message is None: + raise DebugError("failed", "the device ended the stream without answering") + if message.get("t") == "ok": + return + if message.get("t") == "error": + raise _device_error(message) + raise DebugError("bad_request", f"the device answered with '{message.get('t')}' instead of ok") + + +def _device_error(message: Dict[str, Any]) -> DebugError: + code = str(message.get("code", "failed")) + text = str(message.get("text", "")) or "the device refused the operation" + return DebugError(code, text) diff --git a/gui/transferd_gui/debug/policy.py b/gui/transferd_gui/debug/policy.py new file mode 100644 index 0000000..f339c40 --- /dev/null +++ b/gui/transferd_gui/debug/policy.py @@ -0,0 +1,106 @@ +"""The device's debugging policy: whether debugging is on, who may debug, and what each operation may do. + +`decide` is the one place the rule is written down. The agent calls it for every stream a debugger opens, and the +settings page shows the same values, so what the user sees is what the device enforces. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import FrozenSet, Iterable, Tuple + +from transferd_gui.debug.wire import OPS + +#: The modes an operation can have. `ask` means the device's user decides each stream. +MODES: Tuple[str, ...] = ("allow", "ask", "deny") +#: The defaults: reading device information is open; logs, shells and forwards need a yes from the device's user. +DEFAULT_MODES = {"info": "allow", "logcat": "ask", "shell": "ask", "forward": "ask"} +NODE_ID_HEX_LEN = 64 +PORT_MAX = 65535 + + +@dataclass(frozen=True) +class DebugPolicy: + """Every debugging setting the device enforces. The defaults refuse everything except device information, and only + after the user has turned debugging on and named a debugger.""" + + enabled: bool = False + modes: dict = field(default_factory=lambda: dict(DEFAULT_MODES)) + clients: FrozenSet[str] = frozenset() + forward_ports: FrozenSet[int] = frozenset() + shell_timeout_s: float = 60.0 + shell_output_limit: int = 256 * 1024 + streams_per_client: int = 8 + + def mode(self, op: str) -> str: + return self.modes.get(op, "deny") + + def allows_client(self, node_id: str) -> bool: + return node_id in self.clients + + +@dataclass(frozen=True) +class Decision: + """What the device does with one stream. `code` and `reason` are set when it is refused.""" + + outcome: str # "allow", "ask" or "refuse" + code: str = "" + reason: str = "" + + +def decide(policy: DebugPolicy, op: str, client_node_id: str) -> Decision: + """Allow, ask, or refuse a stream from `client_node_id` for `op`. The checks run in the order a user would expect: + the master switch, then the allowlist, then the operation's own mode.""" + if not policy.enabled: + return Decision("refuse", "disabled", "debugging is turned off on this device") + if not policy.allows_client(client_node_id): + return Decision("refuse", "denied", "this computer is not on the device's list of debuggers") + mode = policy.mode(op) + if mode == "deny": + return Decision("refuse", "denied", f"'{op}' is turned off on this device") + if mode == "ask": + return Decision("ask") + return Decision("allow") + + +def parse_ports(text: str) -> FrozenSet[int]: + """`8080, 5555` as a set of ports. Empty text is the empty set. Raises ValueError naming the bad part.""" + ports = set() + for part in _split(text): + if not part.isdigit() or not 1 <= int(part) <= PORT_MAX: + raise ValueError(f"'{part}' is not a port from 1 to {PORT_MAX}") + ports.add(int(part)) + return frozenset(ports) + + +def parse_clients(text: str) -> FrozenSet[str]: + """Node ids, comma separated, each 64 hexadecimal characters. Empty text is the empty set.""" + ids = [] + for part in _split(text): + value = part.lower() + if len(value) != NODE_ID_HEX_LEN or any(c not in "0123456789abcdef" for c in value): + raise ValueError(f"'{part}' is not a node id (64 hexadecimal characters)") + ids.append(value) + return frozenset(ids) + + +def format_ports(ports: Iterable[int]) -> str: + return ", ".join(str(p) for p in sorted(ports)) + + +def format_clients(ids: Iterable[str]) -> str: + return ", ".join(sorted(ids)) + + +def _split(text: str) -> list: + return [part.strip() for part in text.replace(";", ",").split(",") if part.strip()] + + +def check_modes(modes: dict) -> list: + """Problems with a set of operation modes, one message per problem. An empty list means they are valid.""" + problems = [] + for op in OPS: + mode = modes.get(op, DEFAULT_MODES[op]) + if mode not in MODES: + problems.append(f"the {op} mode must be one of: {', '.join(MODES)}") + return problems diff --git a/gui/transferd_gui/debug/providers.py b/gui/transferd_gui/debug/providers.py new file mode 100644 index 0000000..60d5922 --- /dev/null +++ b/gui/transferd_gui/debug/providers.py @@ -0,0 +1,162 @@ +"""The device's real providers: its log command, its shell, its properties, and its loopback ports. + +`log_command` is set by the user in Settings. On Android it is typically `logcat -v time`; on a computer it can be any +command that writes lines. Nothing is read from the device unless the user set it. +""" + +from __future__ import annotations + +import asyncio +import os +import platform +import signal +import subprocess +import sys +from typing import Any, AsyncIterator, Dict, Optional, Tuple + +from transferd_gui.debug.wire import PROTOCOL_VERSION + +#: The longest single line a log command may print. Longer lines end the reader, so the limit is generous. +LOG_LINE_LIMIT = 1 << 20 +#: Bytes read from a process pipe at a time. +PIPE_CHUNK = 16 * 1024 + + +class SystemProviders: + """The providers a real device uses. `node_name` and `node_id` describe the device in `info`.""" + + def __init__(self, *, node_name: str, node_id: str, log_command: str = "") -> None: + self._node_name = node_name + self._node_id = node_id + self._log_command = log_command.strip() + + def info(self) -> Dict[str, Any]: + return { + "node": self._node_name, + "node_id": self._node_id, + "system": f"{platform.system()} {platform.release()}".strip(), + "machine": platform.machine(), + "python": platform.python_version(), + "platform": sys.platform, + "protocol": PROTOCOL_VERSION, + "log_source": "configured" if self._log_command else "not configured", + } + + def log_lines(self, text_filter: str) -> Optional[AsyncIterator[str]]: + if not self._log_command: + return None + return _log_lines(self._log_command, text_filter) + + def run_shell(self, command: str) -> "_ProcessRun": + return _ProcessRun(command) + + async def open_port(self, port: int) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]: + return await asyncio.open_connection("127.0.0.1", port) + + +def _kill_tree(process: asyncio.subprocess.Process) -> None: + """Kill a shell command and everything it started. Killing only the shell leaves its children holding the output + pipes open, and the pipes are what says the command has finished.""" + if process.returncode is not None: + return + if os.name == "nt": + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(process.pid)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=10, + check=False, + ) + return + try: + os.killpg(process.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + process.kill() + + +async def _log_lines(command: str, text_filter: str) -> AsyncIterator[str]: + """The lines `command` prints that contain `text_filter` (case-insensitive). The command is stopped when the + iterator is closed or dropped.""" + process = await _spawn(command, stderr=asyncio.subprocess.STDOUT) + needle = text_filter.lower() + try: + assert process.stdout is not None + while True: + raw = await process.stdout.readline() + if not raw: + break + text = raw.decode("utf-8", errors="replace").rstrip("\r\n") + if needle and needle not in text.lower(): + continue + yield text + finally: + _kill_tree(process) + await process.wait() + + +async def _spawn(command: str, stderr: int) -> asyncio.subprocess.Process: + """Start `command` through the platform's shell, in its own process group where the platform has one.""" + return await asyncio.create_subprocess_shell( + command, + stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, + stderr=stderr, + limit=LOG_LINE_LIMIT, + start_new_session=os.name != "nt", + ) + + +class _ProcessRun: + """A shell command run through the platform's shell. Its output is read as it comes, from both pipes.""" + + def __init__(self, command: str) -> None: + self._command = command + self._process: Optional[asyncio.subprocess.Process] = None + + async def _start(self) -> asyncio.subprocess.Process: + if self._process is None: + self._process = await _spawn(self._command, stderr=asyncio.subprocess.PIPE) + return self._process + + async def output(self) -> AsyncIterator[Tuple[int, bytes]]: + process = await self._start() + assert process.stdout is not None and process.stderr is not None + queue: asyncio.Queue = asyncio.Queue() + + async def pipe(fd: int, stream: asyncio.StreamReader) -> None: + try: + while True: + data = await stream.read(PIPE_CHUNK) + if not data: + break + await queue.put((fd, data)) + finally: + await queue.put(None) + + tasks = [asyncio.create_task(pipe(1, process.stdout)), asyncio.create_task(pipe(2, process.stderr))] + open_pipes = 2 + try: + while open_pipes: + item = await queue.get() + if item is None: + open_pipes -= 1 + continue + yield item + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def wait(self) -> Optional[int]: + process = await self._start() + return await process.wait() + + def kill(self) -> None: + if self._process is not None: + _kill_tree(self._process) + + async def close(self) -> None: + if self._process is None: + return + self.kill() + await self._process.wait() diff --git a/gui/transferd_gui/debug/stream.py b/gui/transferd_gui/debug/stream.py new file mode 100644 index 0000000..13b1bdc --- /dev/null +++ b/gui/transferd_gui/debug/stream.py @@ -0,0 +1,89 @@ +"""The channel a debug operation runs over: bytes one way and the other, a clean end, and an error end. + +The agent and the client are written against this interface and know nothing of overlay sessions. The GUI node adapts an +overlay stream to it (`backend/debugnode.py`), and `pipe_pair` makes an in-memory pair for tests. +""" + +from __future__ import annotations + +import asyncio +from typing import Optional, Protocol, Tuple + + +class Channel(Protocol): + """One end of a debug stream.""" + + async def read(self) -> Optional[bytes]: + """The next bytes from the other end, or None when it has ended (cleanly, or by an error).""" + + async def write(self, data: bytes) -> None: + """Send bytes to the other end.""" + + async def end(self) -> None: + """Half-close: this side has nothing more to send. The other end reads everything written before this, then the + end. This side can still read until the other end ends too. Must not be a full close: a reply still on its way + from the other end must arrive.""" + + async def close(self) -> None: + """Release the channel: nothing more is read or written. The owner calls it once its operation is finished.""" + + async def reset(self, reason: str) -> None: + """End this side with an error. The other end reads what was written before this, then an error.""" + + +class ChannelReset(Exception): + """The other end ended the stream with an error.""" + + +class _Pipe: + def __init__(self) -> None: + self.items: asyncio.Queue = asyncio.Queue() + + +class PipeChannel: + """One end of an in-memory channel. Writes arrive at the other end in order. Used by tests, and by anything that + needs a channel without a network.""" + + def __init__(self, inbox: _Pipe, outbox: _Pipe) -> None: + self._inbox = inbox + self._outbox = outbox + self._ended = False + self._peer_done = False + + async def read(self) -> Optional[bytes]: + if self._peer_done: + return None + item = await self._inbox.items.get() + if item is None: + self._peer_done = True + return None + kind, value = item + if kind == "reset": + self._peer_done = True + raise ChannelReset(value) + return value + + async def write(self, data: bytes) -> None: + if self._ended: + raise ChannelReset("the stream is already ended") + await self._outbox.items.put(("data", data)) + + async def end(self) -> None: + if not self._ended: + self._ended = True + await self._outbox.items.put(None) + + async def close(self) -> None: + await self.end() + self._peer_done = True + + async def reset(self, reason: str) -> None: + if not self._ended: + self._ended = True + await self._outbox.items.put(("reset", reason)) + + +def pipe_pair() -> Tuple[PipeChannel, PipeChannel]: + """Two connected ends: what one writes, the other reads.""" + a_to_b, b_to_a = _Pipe(), _Pipe() + return PipeChannel(b_to_a, a_to_b), PipeChannel(a_to_b, b_to_a) diff --git a/gui/transferd_gui/debug/usb.py b/gui/transferd_gui/debug/usb.py new file mode 100644 index 0000000..0c5779e --- /dev/null +++ b/gui/transferd_gui/debug/usb.py @@ -0,0 +1,111 @@ +"""The USB route: Android's `adb` carries a TCP connection over the cable with `adb forward`. + +The bridge makes no protocol of its own. `adb forward tcp:L tcp:P` makes the device's Transferd listener (port P, on the +device) reachable at 127.0.0.1:L on the computer. The node dials that address with the ordinary handshake and adds it to +the device's session as a route. So a USB route is a loopback TCP route, and everything above it is unchanged. + +Every failure of `adb` becomes an `AdbError` with a sentence a user can act on. +""" + +from __future__ import annotations + +import socket +import subprocess +from dataclasses import dataclass +from typing import List, Sequence, Union + +#: How long one `adb` command may take. `adb` talks to its server, which normally answers at once. +ADB_TIMEOUT_S = 15.0 + +#: The words adb uses for a device's state, and what the user should do about each one that is not `device`. +STATE_HELP = { + "device": "ready", + "unauthorized": "allow USB debugging on the phone (accept the prompt that appears there)", + "offline": "the phone is offline; unplug it, plug it in again, and accept the prompt if one appears", + "bootloader": "the phone is in the bootloader; start Android to debug it", + "recovery": "the phone is in recovery mode; start Android to debug it", + "sideload": "the phone is in sideload mode; start Android to debug it", +} + + +@dataclass(frozen=True) +class AdbDevice: + serial: str + state: str + model: str = "" + + @property + def ready(self) -> bool: + return self.state == "device" + + @property + def help(self) -> str: + return STATE_HELP.get(self.state, f"adb reports the state '{self.state}'") + + +class AdbError(Exception): + """`adb` is missing, failed, or timed out. The message says what to do.""" + + +def parse_devices(text: str) -> List[AdbDevice]: + """The devices in `adb devices -l` output. Header and blank lines are skipped; the model comes from `model:`.""" + devices: List[AdbDevice] = [] + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith("List of devices") or line.startswith("*"): + continue + parts = line.split() + if len(parts) < 2: + continue + model = next((p.split(":", 1)[1] for p in parts[2:] if p.startswith("model:")), "") + devices.append(AdbDevice(serial=parts[0], state=parts[1], model=model.replace("_", " "))) + return devices + + +def free_local_port() -> int: + """A loopback port that is free now. The forward binds it a moment later; the caller retries if that fails.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: + probe.bind(("127.0.0.1", 0)) + return int(probe.getsockname()[1]) + + +class Adb: + """The `adb` program, run as a subprocess. `program` is the path or the command, as a string or a list.""" + + def __init__(self, program: Union[str, Sequence[str]] = "adb") -> None: + self._program = [program] if isinstance(program, str) else list(program) + + def _run(self, *args: str) -> str: + try: + done = subprocess.run( + [*self._program, *args], + capture_output=True, + text=True, + timeout=ADB_TIMEOUT_S, + check=False, + ) + except FileNotFoundError as exc: + raise AdbError( + f"adb was not found at '{self._program[0]}'. Install Android platform-tools, or set the adb path in Settings." + ) from exc + except subprocess.TimeoutExpired as exc: + raise AdbError("adb did not answer in time; its server may be stuck (try 'adb kill-server')") from exc + except OSError as exc: + raise AdbError(f"adb could not be started: {exc.strerror or exc}") from exc + if done.returncode != 0: + detail = (done.stderr or done.stdout or "").strip().splitlines() + raise AdbError(detail[-1] if detail else f"adb exited with code {done.returncode}") + return done.stdout + + def devices(self) -> List[AdbDevice]: + return parse_devices(self._run("devices", "-l")) + + def forward(self, serial: str, local_port: int, device_port: int) -> None: + self._run("-s", serial, "forward", f"tcp:{local_port}", f"tcp:{device_port}") + + def remove_forward(self, local_port: int) -> None: + self._run("forward", "--remove", f"tcp:{local_port}") + + def version(self) -> str: + out = self._run("version").strip() + return out.splitlines()[0] if out else "" diff --git a/gui/transferd_gui/debug/wire.py b/gui/transferd_gui/debug/wire.py new file mode 100644 index 0000000..38a7ce7 --- /dev/null +++ b/gui/transferd_gui/debug/wire.py @@ -0,0 +1,146 @@ +"""The debug protocol's messages (see `gui/docs/DEBUG_PROTOCOL.md`): one JSON object per line on an overlay stream. + +Nothing here touches a socket or a session. It turns messages into bytes and bytes back into messages, and it refuses +anything that breaks a limit, so a misbehaving peer cannot make the other side buffer without bound. +""" + +from __future__ import annotations + +import base64 +import json +from typing import Any, Dict, List, Optional + +PROTOCOL_VERSION = 1 +#: Overlay services for the debug operations. No dots: a Rust node's `expose` refuses them. +SERVICE_PREFIX = "debug-" +OPS = ("info", "logcat", "shell", "forward") + +MAX_REQUEST = 4096 +MAX_LINE = 64 * 1024 +MAX_TEXT = 4096 +MAX_SHELL_COMMAND = 2048 +MAX_SHELL_TIMEOUT_S = 600.0 + +#: Every error code the protocol uses. A receiver shows an unknown code as it is. +ERROR_CODES = ( + "denied", + "disabled", + "not_allowed", + "bad_request", + "unsupported_version", + "unavailable", + "failed", + "too_many", + "timeout", +) + + +class WireError(ValueError): + """A message that breaks the protocol: not JSON, not an object, too long, or missing a required field.""" + + +def service_name(op: str) -> str: + if op not in OPS: + raise WireError(f"unknown debug operation '{op}'") + return SERVICE_PREFIX + op + + +def op_of(service: str) -> Optional[str]: + """The operation a service name stands for, or None when it is not a debug service.""" + if not service.startswith(SERVICE_PREFIX): + return None + op = service[len(SERVICE_PREFIX):] + return op if op in OPS else None + + +def encode(message: Dict[str, Any], limit: int = MAX_LINE) -> bytes: + """One message as a line of UTF-8 JSON ending in a newline. Raises WireError when it is too long for `limit`.""" + try: + text = json.dumps(message, separators=(",", ":"), ensure_ascii=False) + except (TypeError, ValueError) as exc: + raise WireError(f"the message cannot be encoded: {exc}") from exc + data = text.encode("utf-8") + b"\n" + if len(data) > limit: + raise WireError(f"the message is {len(data)} bytes, over the {limit} byte limit") + return data + + +def request(args: Dict[str, Any]) -> bytes: + """The first line a client sends on a debug stream.""" + return encode({"v": PROTOCOL_VERSION, "args": args}, MAX_REQUEST) + + +def parse(line: bytes) -> Dict[str, Any]: + """One received line as a message. It must be a JSON object with a string `t` (for responses) or a `v` (for requests).""" + try: + message = json.loads(line.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise WireError(f"a line is not UTF-8 JSON: {exc}") from exc + if not isinstance(message, dict): + raise WireError("a line is not a JSON object") + return message + + +class LineDecoder: + """Turns bytes that arrive in pieces into whole messages, one line at a time. + + `push` adds bytes; `take` returns the next complete message, or None when the buffer holds no whole line. Bytes + after the line just taken stay buffered: `rest` returns them. That is how a raw forward reads the bytes that came + in with its request line, without parsing them as JSON. + """ + + def __init__(self, limit: int = MAX_LINE) -> None: + self._limit = limit + self._buffer = bytearray() + + def push(self, chunk: bytes) -> None: + self._buffer += chunk + + def take(self) -> Optional[Dict[str, Any]]: + end = self._buffer.find(b"\n") + if end < 0: + if len(self._buffer) > self._limit: + raise WireError(f"a line is longer than {self._limit} bytes") + return None + if end > self._limit: + raise WireError(f"a line is longer than {self._limit} bytes") + line = bytes(self._buffer[:end]) + del self._buffer[: end + 1] + return parse(line) + + def take_all(self) -> List[Dict[str, Any]]: + """Every complete message now buffered.""" + messages = [] + while True: + message = self.take() + if message is None: + return messages + messages.append(message) + + def feed(self, chunk: bytes) -> List[Dict[str, Any]]: + self.push(chunk) + return self.take_all() + + def rest(self) -> bytes: + """The buffered bytes that are not yet a message, emptied. For a raw stream after its first line.""" + data = bytes(self._buffer) + self._buffer.clear() + return data + + +def b64(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def unb64(text: str) -> bytes: + try: + return base64.b64decode(text.encode("ascii"), validate=True) + except (ValueError, UnicodeEncodeError) as exc: + raise WireError(f"bytes are not base64: {exc}") from exc + + +def clip_text(text: str, limit: int = MAX_TEXT) -> tuple[str, bool]: + """`text` cut to `limit` characters, and whether it was cut.""" + if len(text) <= limit: + return text, False + return text[:limit], True diff --git a/gui/transferd_gui/model/settings.py b/gui/transferd_gui/model/settings.py index 0160743..ae7e77a 100644 --- a/gui/transferd_gui/model/settings.py +++ b/gui/transferd_gui/model/settings.py @@ -14,8 +14,15 @@ from pathlib import Path from typing import Any, List, Mapping, Tuple +from transferd_gui.debug.policy import MODES, parse_clients, parse_ports +from transferd_gui.wormhole.addresses import parse_list + THEMES: Tuple[str, ...] = ("system", "light", "dark") +#: How the debugging computer reaches a device that is also paired over Wi-Fi or the relay. +DEBUG_TRANSPORTS: Tuple[str, ...] = ("auto", "usb_only", "wifi_only") NODE_NAME_MAX = 64 +#: The longest path or command text the debugging settings accept. +TEXT_MAX = 512 class SettingsError(ValueError): @@ -44,6 +51,37 @@ class Settings: theme: str = "system" event_log_size: int = 500 telemetry_window_s: int = 600 + # Debugging, as a device (the agent): whether this node answers debug streams, who may ask, and what each may do. + debug_enabled: bool = False + debug_clients: str = "" + debug_info_mode: str = "allow" + debug_logcat_mode: str = "ask" + debug_shell_mode: str = "ask" + debug_forward_mode: str = "ask" + debug_forward_ports: str = "" + debug_log_command: str = "" + debug_shell_timeout_s: float = 60.0 + debug_shell_output_kib: int = 256 + debug_streams_per_client: int = 8 + # Debugging, as a computer (the client): which device it debugs, how it reaches it, and the USB bridge. + debug_device_id: str = "" + debug_transport: str = "auto" + debug_wifi_address: str = "" + usb_adb_path: str = "adb" + usb_device_port: int = 0 + + #: The mailboxes a wormhole may meet on, a comma-separated list tried in order: wss://host:port#fingerprint for another + #: computer (the fingerprint pins its certificate), or ws://127.0.0.1:port for this one. Empty means none is set. + wormhole_mailbox: str = "" + #: How many data streams a wormhole file is spread over. + wormhole_streams: int = 4 + #: Host a mailbox on this computer. Off until it is turned on; nothing listens while it is off. + wormhole_host: bool = False + #: The port the hosted mailbox listens on. + wormhole_host_port: int = 4470 + #: Whether the hosted mailbox is reachable from other computers: wss:// with its own pinned certificate. Off means only + #: this computer, over ws://127.0.0.1. + wormhole_host_network: bool = False # Each integer or float setting with its inclusive bounds. Bools and strings are checked separately. @@ -54,8 +92,17 @@ class Settings: "max_transfer_mib": (1, 512, int), "event_log_size": (50, 10000, int), "telemetry_window_s": (60, 3600, int), + "debug_shell_timeout_s": (1.0, 600.0, float), + "debug_shell_output_kib": (16, 16384, int), + "debug_streams_per_client": (1, 64, int), + "usb_device_port": (0, 65535, int), + "wormhole_streams": (1, 8, int), + "wormhole_host_port": (1, 65535, int), } +#: The longest mailbox list Settings accepts: up to four addresses, each with its pin. +WORMHOLE_MAILBOX_MAX = 600 + def parse_host_port(text: str) -> Tuple[str, int]: """Split `host:port` or `[ipv6]:port` into its parts. Raises ValueError with a message a user can act on.""" @@ -107,9 +154,20 @@ def validate(raw: Mapping[str, Any]) -> Settings: parse_host_port(value) except ValueError as exc: problems.append(f"{key}: {exc}") - for key in ("allow_incoming", "auto_accept_files"): + for key in ("allow_incoming", "auto_accept_files", "debug_enabled", "wormhole_host", "wormhole_host_network"): if not isinstance(values.get(key, False), bool): problems.append(f"{key} must be on or off") + mailbox = values.get("wormhole_mailbox", defaults["wormhole_mailbox"]) + if not isinstance(mailbox, str): + problems.append("wormhole_mailbox must be text") + elif len(mailbox) > WORMHOLE_MAILBOX_MAX: + problems.append(f"wormhole_mailbox is longer than {WORMHOLE_MAILBOX_MAX} characters") + else: + try: + parse_list(mailbox) + except ValueError as exc: + problems.append(f"wormhole_mailbox: {exc}") + problems.extend(_debug_problems(values, defaults)) if values.get("theme", defaults["theme"]) not in THEMES: problems.append(f"theme must be one of: {', '.join(THEMES)}") for key, (low, high, kind) in _NUMBER_RANGES.items(): @@ -134,6 +192,52 @@ def validate(raw: Mapping[str, Any]) -> Settings: return Settings(**merged) +def _debug_problems(values: Mapping[str, Any], defaults: Mapping[str, Any]) -> List[str]: + """Problems with the debugging settings. Each text value is checked as the protocol will read it.""" + problems: List[str] = [] + + def text(key: str) -> str: + value = values.get(key, defaults[key]) + return value if isinstance(value, str) else "" + + for key in ("debug_clients", "debug_forward_ports", "debug_device_id", "debug_wifi_address", "debug_log_command", "usb_adb_path", "debug_transport"): + if not isinstance(values.get(key, defaults[key]), str): + problems.append(f"{key} must be text") + if problems: + return problems + try: + parse_clients(text("debug_clients")) + except ValueError as exc: + problems.append(f"debug_clients: {exc}") + try: + parse_ports(text("debug_forward_ports")) + except ValueError as exc: + problems.append(f"debug_forward_ports: {exc}") + if text("debug_device_id").strip(): + try: + parse_clients(text("debug_device_id")) + except ValueError as exc: + problems.append(f"debug_device_id: {exc}") + if text("debug_wifi_address").strip(): + try: + parse_host_port(text("debug_wifi_address")) + except ValueError as exc: + problems.append(f"debug_wifi_address: {exc}") + for key in ("debug_log_command", "usb_adb_path"): + value = text(key) + if len(value) > TEXT_MAX or any(ord(c) < 32 for c in value): + problems.append(f"{key} must be at most {TEXT_MAX} characters without control characters") + if not text("usb_adb_path").strip(): + problems.append("usb_adb_path must name the adb program, or be 'adb' to use the one on PATH") + if text("debug_transport") not in DEBUG_TRANSPORTS: + problems.append(f"debug_transport must be one of: {', '.join(DEBUG_TRANSPORTS)}") + modes = {op: values.get(f"debug_{op}_mode", defaults[f"debug_{op}_mode"]) for op in ("info", "logcat", "shell", "forward")} + for key, mode in modes.items(): + if mode not in MODES: + problems.append(f"debug_{key}_mode must be one of: {', '.join(MODES)}") + return problems + + def updated(current: Settings, changes: Mapping[str, Any]) -> Settings: """The settings with `changes` applied, validated as a whole. Raises `SettingsError` and changes nothing.""" return validate({**asdict(current), **changes}) diff --git a/gui/transferd_gui/model/snapshot.py b/gui/transferd_gui/model/snapshot.py index 2a41775..c432146 100644 --- a/gui/transferd_gui/model/snapshot.py +++ b/gui/transferd_gui/model/snapshot.py @@ -26,6 +26,8 @@ class RouteSnapshot: kind: str up: bool closed: bool + #: What the route is: its address, or `usb:` for a route carried over the cable. + label: str = "" #: Library measurements. None until the route has answered a probe. An RTT of 0.0 is real: it is under the #: platform's clock resolution. rtt_ms: Optional[float] = None @@ -121,6 +123,41 @@ class LocateResult: punch_candidates: Tuple[str, ...] = () +@dataclass(frozen=True) +class UsbDeviceSnapshot: + """A device adb reported. `state` is adb's word: `device` (ready), `unauthorized`, `offline` and so on.""" + + serial: str + state: str + model: str = "" + + +@dataclass(frozen=True) +class DebugStreamSnapshot: + """A debug operation this node is running as a debugger: a log stream, a shell command or a port forward.""" + + handle: int + peer_id: str + kind: str + detail: str + started_at: float + state: str + note: str = "" + + +@dataclass(frozen=True) +class DebugSnapshot: + """Debugging on this node, in both roles, and what the USB bridge can see.""" + + agent_enabled: bool = False + clients: Tuple[str, ...] = () + device_id: str = "" + usb_state: str = "not checked" + usb_detail: str = "" + usb_devices: Tuple[UsbDeviceSnapshot, ...] = () + streams: Tuple[DebugStreamSnapshot, ...] = () + + @dataclass(frozen=True) class NodeSnapshot: taken_at: float @@ -131,6 +168,7 @@ class NodeSnapshot: requests: Tuple[IncomingRequest, ...] = () transfers: Tuple[TransferRecord, ...] = () locate: Optional[LocateResult] = None + debug: DebugSnapshot = DebugSnapshot() @property def all_routes(self) -> Tuple[RouteSnapshot, ...]: @@ -142,3 +180,6 @@ def routes_up(self) -> int: def ready_peers(self) -> Tuple[SessionSnapshot, ...]: return tuple(session for session in self.sessions if session.state == "ready") + + def session_for(self, peer_id: str) -> Optional[SessionSnapshot]: + return next((session for session in self.sessions if session.peer_id == peer_id), None) diff --git a/gui/transferd_gui/ui/main_window.py b/gui/transferd_gui/ui/main_window.py index ee14ebb..c5bf97f 100644 --- a/gui/transferd_gui/ui/main_window.py +++ b/gui/transferd_gui/ui/main_window.py @@ -31,6 +31,7 @@ from transferd_gui.ui.bridge import Bridge from transferd_gui.ui.pages.base import Context, Page from transferd_gui.ui.pages.dashboard import DashboardPage +from transferd_gui.ui.pages.debug import DebugPage from transferd_gui.ui.pages.dns import DnsPage from transferd_gui.ui.pages.events import EventsPage from transferd_gui.ui.pages.ghost import GhostPage @@ -41,6 +42,7 @@ from transferd_gui.ui.pages.relay import RelayPage from transferd_gui.ui.pages.settings import SettingsPage from transferd_gui.ui.pages.transfer import TransferPage +from transferd_gui.ui.pages.wormhole import WormholePage from transferd_gui.ui.status import relay_status from transferd_gui.ui.widgets import Notice, Pill @@ -48,8 +50,9 @@ NAVIGATION: Sequence[tuple] = ( ("Overview", (DashboardPage,)), ("Network", (IdentityPage, RelayPage, PeersPage, InvitesPage)), - ("Transfer", (TransferPage, PunchPage)), + ("Transfer", (TransferPage, WormholePage, PunchPage)), ("Tools", (DnsPage, GhostPage)), + ("Debug", (DebugPage,)), ("System", (EventsPage, SettingsPage)), ) #: Ghost key files are read about every this many snapshots (about every five seconds). diff --git a/gui/transferd_gui/ui/pages/debug.py b/gui/transferd_gui/ui/pages/debug.py new file mode 100644 index 0000000..69b0e01 --- /dev/null +++ b/gui/transferd_gui/ui/pages/debug.py @@ -0,0 +1,575 @@ +"""Debugging: choose a device, connect a route to it over Wi-Fi or USB, then read its information or log, run a command on it, +or forward a port. The device decides what it allows. A request a device's user is asked about waits here until it is +answered, and every operation running now is listed with its state.""" + +from __future__ import annotations + +import time +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from PySide6.QtWidgets import QComboBox, QHBoxLayout, QLabel, QLineEdit, QPlainTextEdit, QPushButton, QSpinBox + +from transferd_gui.debug import wire +from transferd_gui.debug.usb import AdbDevice +from transferd_gui.model.fmt import short_hex +from transferd_gui.model.settings import Settings, SettingsError +from transferd_gui.model.snapshot import NodeSnapshot +from transferd_gui.ui.pages.base import Page +from transferd_gui.ui.widgets import ActionRow, Card, Notice, Pill, TableWithEmpty + +#: Lines kept in each text view. Older lines are dropped, so a long log never grows without limit. +VIEW_LINES = 2000 +INFO_SERVICE = wire.service_name("info") +TRANSPORT_LABELS = { + "auto": "USB when it is plugged in, otherwise Wi-Fi", + "usb_only": "USB only", + "wifi_only": "Wi-Fi only", +} + + +def is_node_id(text: str) -> bool: + return len(text) == 64 and all(c in "0123456789abcdef" for c in text) + + +def device_state(snapshot: NodeSnapshot, device_id: str) -> Tuple[str, str]: + """What the chosen device is, for this computer, as a short word and a tone.""" + if not device_id: + return "no device chosen", "idle" + session = snapshot.session_for(device_id) + if session is None: + return "not connected", "warn" + if not session.routes_up: + return "no live route", "warn" + if INFO_SERVICE not in session.services: + return "does not offer debugging", "warn" + return "ready", "ok" + + +def _text(value: Any) -> str: + if isinstance(value, (bytes, bytearray)): + return bytes(value).decode("utf-8", errors="replace") + return str(value) + + +class DebugPage(Page): + key = "debug" + title = "Debugging" + explainer = ( + "Debug a device over USB, over Wi-Fi, or both. Choose the device, connect a route to it, then read its information " + "or log, run a command on it, or forward a port. The device's own settings decide what it allows." + ) + + def build(self) -> None: + self._shown: Dict[str, Any] = {} + self._peer_ids: List[str] = [] + self._usb_serials: List[str] = [] + self._stream_handles: List[int] = [] + self._request_ids: List[int] = [] + self._log_handle: Optional[int] = None + # The log's lines arrive on the backend thread; this turns each one into a call on the UI thread. + self._log_sink = self.bridge.on_ui(self._on_log_message) + + self._build_this_device() + self._build_choice() + self._build_connection() + self._build_log() + self._build_shell() + self._build_forward() + self._build_operations() + self._build_requests() + self.on_settings(self.service.settings) + + # ----- construction ------------------------------------------------------------------------- + + def _build_this_device(self) -> None: + card = Card("This device") + self.device_side = Notice() + card.body.addWidget(self.device_side) + self.content.addWidget(card) + + def _build_choice(self) -> None: + card = Card("Device to debug") + card.body.addWidget(QLabel("Pick a peer you are connected to, or paste its node id. Everything below uses this device.")) + row = QHBoxLayout() + self.peer_combo = QComboBox() + self.peer_combo.setMinimumWidth(260) + self.device_edit = QLineEdit() + self.device_edit.setPlaceholderText("device node id (64 hex characters)") + self.use_button = QPushButton("Use this device") + self.use_button.clicked.connect(self._use_device) + row.addWidget(self.peer_combo, 1) + row.addWidget(self.device_edit, 2) + row.addWidget(self.use_button) + card.body.addLayout(row) + status = QHBoxLayout() + self.device_pill = Pill("no device chosen", "idle") + self.ask_button = QPushButton("Ask the device for its information") + self.ask_button.clicked.connect(self._ask_info) + status.addWidget(self.device_pill) + status.addWidget(self.ask_button) + status.addStretch(1) + card.body.addLayout(status) + self.choice_notice = Notice() + card.body.addWidget(self.choice_notice) + self.content.addWidget(card) + + def _build_connection(self) -> None: + card = Card("Connection") + self.transport_text = QLabel() + self.transport_text.setWordWrap(True) + card.body.addWidget(self.transport_text) + self.routes = TableWithEmpty( + ("Route", "Kind", "State", "Received", "Sent"), + "No route to this device yet. Connect over Wi-Fi or USB below.", + ) + card.body.addWidget(self.routes) + + self.wifi_button = QPushButton("Connect over Wi-Fi") + self.wifi_button.clicked.connect(self._connect_wifi) + card.body.addWidget(ActionRow(self.wifi_button)) + + card.body.addWidget(QLabel("USB: plug the phone in, allow USB debugging on it, then look for it.")) + self.usb_state = Notice() + card.body.addWidget(self.usb_state) + self.usb_table = TableWithEmpty(("Serial", "State", "Model", "What to do"), "No USB devices looked for yet.") + card.body.addWidget(self.usb_table) + self.usb_scan_button = QPushButton("Look for USB devices") + self.usb_scan_button.clicked.connect(self._scan_usb) + self.usb_connect_button = QPushButton("Connect the selected USB device") + self.usb_connect_button.clicked.connect(self._connect_usb) + card.body.addWidget(ActionRow(self.usb_scan_button, self.usb_connect_button)) + + self.connection_notice = Notice() + card.body.addWidget(self.connection_notice) + self.content.addWidget(card) + + def _build_log(self) -> None: + card = Card("Log") + card.body.addWidget(QLabel("The device's log as it is written. Filter by text if you want (optional).")) + row = QHBoxLayout() + self.log_filter = QLineEdit() + self.log_filter.setPlaceholderText("only lines containing (optional)") + self.log_start = QPushButton("Start") + self.log_start.clicked.connect(self._start_log) + self.log_stop = QPushButton("Stop") + self.log_stop.clicked.connect(self._stop_log) + self.log_clear = QPushButton("Clear") + self.log_clear.clicked.connect(lambda: self.log_view.clear()) + row.addWidget(self.log_filter, 1) + row.addWidget(self.log_start) + row.addWidget(self.log_stop) + row.addWidget(self.log_clear) + card.body.addLayout(row) + self.log_view = QPlainTextEdit() + self.log_view.setReadOnly(True) + self.log_view.setMaximumBlockCount(VIEW_LINES) + self.log_view.setMinimumHeight(160) + card.body.addWidget(self.log_view) + self.log_notice = Notice() + card.body.addWidget(self.log_notice) + self.content.addWidget(card) + + def _build_shell(self) -> None: + card = Card("Run a command") + card.body.addWidget(QLabel( + "The command runs on the device. Its user is asked first, unless the device's settings allow commands." + )) + row = QHBoxLayout() + self.command = QLineEdit() + self.command.setPlaceholderText("command to run on the device") + self.command.returnPressed.connect(self._run_shell) + self.shell_timeout = QSpinBox() + self.shell_timeout.setRange(1, 600) + self.shell_timeout.setValue(60) + self.shell_timeout.setSuffix(" s") + self.shell_timeout.setToolTip("The command is stopped after this long.") + self.shell_run = QPushButton("Run") + self.shell_run.clicked.connect(self._run_shell) + row.addWidget(self.command, 1) + row.addWidget(self.shell_timeout) + row.addWidget(self.shell_run) + card.body.addLayout(row) + self.shell_output = QPlainTextEdit() + self.shell_output.setReadOnly(True) + self.shell_output.setMaximumBlockCount(VIEW_LINES) + self.shell_output.setMinimumHeight(120) + card.body.addWidget(self.shell_output) + self.shell_notice = Notice() + card.body.addWidget(self.shell_notice) + self.content.addWidget(card) + + def _build_forward(self) -> None: + card = Card("Forward a port") + card.body.addWidget(QLabel( + "Connections to a port on this computer are carried to a port on the device, for example a debugger's port. " + "The device must list the port in its settings." + )) + row = QHBoxLayout() + self.local_port = QSpinBox() + self.local_port.setRange(0, 65535) + self.local_port.setSpecialValueText("any free port") + self.local_port.setPrefix("this computer: ") + self.device_port = QSpinBox() + self.device_port.setRange(1, 65535) + self.device_port.setValue(8080) + self.device_port.setPrefix("device: ") + self.forward_start = QPushButton("Start forwarding") + self.forward_start.clicked.connect(self._start_forward) + row.addWidget(self.local_port) + row.addWidget(self.device_port) + row.addWidget(self.forward_start) + row.addStretch(1) + card.body.addLayout(row) + self.forward_notice = Notice() + card.body.addWidget(self.forward_notice) + self.content.addWidget(card) + + def _build_operations(self) -> None: + card = Card("Operations") + self.streams = TableWithEmpty( + ("Operation", "Device", "Detail", "State", "Note"), + "No debugging operations yet. Logs, commands and forwards you start are listed here.", + ) + card.body.addWidget(self.streams) + self.stop_stream = QPushButton("Stop selected") + self.stop_stream.clicked.connect(self._stop_selected) + card.body.addWidget(ActionRow(self.stop_stream)) + self.operations_notice = Notice() + card.body.addWidget(self.operations_notice) + self.content.addWidget(card) + + def _build_requests(self) -> None: + card = Card("Requests from computers") + card.body.addWidget(QLabel( + "A computer asks to debug this device, or to run a command on it. Accept or refuse each request. " + "Requests wait here until you answer them." + )) + self.requests = TableWithEmpty(("From", "Operation", "Asked at"), "No computer is waiting to debug this device.") + card.body.addWidget(self.requests) + self.accept_button = QPushButton("Accept") + self.accept_button.clicked.connect(lambda: self._answer(True)) + self.refuse_button = QPushButton("Refuse") + self.refuse_button.clicked.connect(lambda: self._answer(False)) + card.body.addWidget(ActionRow(self.accept_button, self.refuse_button)) + self.requests_notice = Notice() + card.body.addWidget(self.requests_notice) + self.content.addWidget(card) + + # ----- snapshots and settings --------------------------------------------------------------- + + def apply(self, snapshot: NodeSnapshot) -> None: + device = self._device() + self._show_device_side(snapshot) + self._show_peers(snapshot) + state, tone = device_state(snapshot, device) + self.device_pill.set_status(state, tone) + self._show_routes(snapshot, device) + self._show_usb(snapshot) + self._show_streams(snapshot) + self._show_requests(snapshot) + self._follow_log(snapshot) + self._enable_actions(device) + + def on_settings(self, settings: Settings) -> None: + address = settings.debug_wifi_address or "not set (Settings, under Debugging from this computer)" + self.transport_text.setText( + f"Transport: {TRANSPORT_LABELS.get(settings.debug_transport, settings.debug_transport)}. " + f"Wi-Fi address: {address}." + ) + + def _show_device_side(self, snapshot: NodeSnapshot) -> None: + debug = snapshot.debug + if not debug.agent_enabled: + text = "Debugging is off on this device, so no computer can debug it. Turn it on in Settings, under Debugging." + elif not debug.clients: + text = "Debugging is on, but no computer is on this device's list yet. Add one in Settings, under Debugging." + else: + count = len(debug.clients) + text = f"Debugging is on. {count} computer{'s' if count != 1 else ''} on the list can use this device." + self.device_side.set_text(text, "muted") + + def _show_peers(self, snapshot: NodeSnapshot) -> None: + ids = [s.peer_id for s in snapshot.sessions] + if ids == self._peer_ids: + return + names = {s.peer_id: s.peer_name for s in snapshot.sessions} + current = self.peer_combo.currentData() + self._peer_ids = ids + self.peer_combo.clear() + for peer_id in ids: + self.peer_combo.addItem(f"{names[peer_id]} ({short_hex(peer_id, 10, 6)})", peer_id) + index = self.peer_combo.findData(current) + if index >= 0: + self.peer_combo.setCurrentIndex(index) + + def _show_routes(self, snapshot: NodeSnapshot, device: str) -> None: + session = snapshot.session_for(device) if device else None + rows = [] + if session is not None: + for route in session.routes: + status = "closed" if route.closed else ("up" if route.up else "down") + rows.append((route.label or route.kind, route.kind, status, f"{route.received_bytes} bytes", f"{route.sent_bytes} bytes")) + self._refresh("routes", self.routes, rows) + + def _show_usb(self, snapshot: NodeSnapshot) -> None: + debug = snapshot.debug + self.usb_state.set_text(debug.usb_detail or "USB has not been checked yet.", "muted") + rows, serials = [], [] + for device in debug.usb_devices: + help_text = AdbDevice(device.serial, device.state, device.model).help + rows.append((device.serial, device.state, device.model or "unknown model", help_text)) + serials.append(device.serial) + self._usb_serials = serials + self._refresh("usb", self.usb_table, rows) + + def _show_streams(self, snapshot: NodeSnapshot) -> None: + rows, handles = [], [] + for stream in sorted(snapshot.debug.streams, key=lambda s: s.handle): + rows.append((stream.kind, short_hex(stream.peer_id, 10, 6), stream.detail, stream.state, stream.note)) + handles.append(stream.handle) + self._stream_handles = handles + self._refresh("streams", self.streams, rows) + + def _show_requests(self, snapshot: NodeSnapshot) -> None: + rows, ids = [], [] + for request in snapshot.requests: + op = wire.op_of(request.service) + if op is None: + continue # file and stream requests are answered on the Transfer screen + rows.append((request.peer_name, op, time.strftime("%H:%M:%S", time.localtime(request.received_at)))) + ids.append(request.request_id) + self._request_ids = ids + self._refresh("requests", self.requests, rows) + + def _follow_log(self, snapshot: NodeSnapshot) -> None: + if self._log_handle is None: + return + stream = next((s for s in snapshot.debug.streams if s.handle == self._log_handle), None) + if stream is None or stream.state != "running": + self._log_handle = None + detail = stream.note if stream is not None and stream.note else "the log ended" + self.log_notice.set_text(f"The log stopped: {detail}.", "muted") + + def _enable_actions(self, device: str) -> None: + self.ask_button.setEnabled(bool(device)) + self.wifi_button.setEnabled(bool(device)) + self.usb_connect_button.setEnabled(bool(device) and bool(self._usb_serials)) + self.log_start.setEnabled(bool(device) and self._log_handle is None) + self.log_stop.setEnabled(self._log_handle is not None) + self.shell_run.setEnabled(bool(device)) + self.forward_start.setEnabled(bool(device)) + self.stop_stream.setEnabled(bool(self._stream_handles)) + self.accept_button.setEnabled(bool(self._request_ids)) + self.refuse_button.setEnabled(bool(self._request_ids)) + + def _refresh(self, name: str, table: TableWithEmpty, rows: Sequence[Tuple[str, ...]]) -> None: + """Replace a table's rows only when they changed, so a selected row survives the once-a-second update.""" + rows = [tuple(r) for r in rows] + if self._shown.get(name) == rows: + return + self._shown[name] = rows + table.set_rows(rows) + + def _device(self) -> str: + return self.service.settings.debug_device_id + + def _need_device(self, notice: Notice) -> Optional[str]: + device = self._device() + if not device: + notice.set_text("Choose the device first: pick a connected peer, or paste its node id, then press Use this device.", "error") + return None + return device + + # ----- device choice ------------------------------------------------------------------------ + + def _use_device(self) -> None: + typed = self.device_edit.text().strip().lower() + chosen = typed or (self.peer_combo.currentData() or "") + if not chosen: + self.choice_notice.set_text("Pick a connected peer, or paste its node id first.", "error") + return + if not is_node_id(chosen): + self.choice_notice.set_text("A node id is 64 lowercase hex characters.", "error") + return + try: + self.service.change_settings({"debug_device_id": chosen}) + except (SettingsError, OSError) as exc: + self.choice_notice.set_text(f"Not changed: {exc}", "error") + return + self.device_edit.clear() + self.choice_notice.set_text(f"Debugging {short_hex(chosen, 10, 6)} from now on.", "ok") + + def _ask_info(self) -> None: + device = self._need_device(self.choice_notice) + if device is None: + return + self.choice_notice.set_text("Asking the device...", "muted") + self.run(self.service.node.debug_info(device), "ask the device for its information", self._info_done) + + def _info_done(self, ok: bool, value: Any) -> None: + if not ok: + self.choice_notice.set_text(f"The device did not answer: {value}", "error") + return + keys = ("node", "system", "machine", "python", "protocol", "log_source") + lines = [f"{key.replace('_', ' ')}: {value[key]}" for key in keys if key in value] + self.choice_notice.set_text("Device information. " + "; ".join(lines) + ".", "ok") + + # ----- connection --------------------------------------------------------------------------- + + def _connect_wifi(self) -> None: + device = self._need_device(self.connection_notice) + if device is None: + return + self.connection_notice.set_text("Connecting over Wi-Fi...", "muted") + self.run(self.service.node.debug_connect_wifi(), "connect over Wi-Fi", self._connected("Wi-Fi")) + + def _scan_usb(self) -> None: + self.run(self.service.node.debug_scan_usb(), "look for USB devices", self._scanned) + + def _scanned(self, ok: bool, value: Any) -> None: + if ok: + count = len(value) + self.connection_notice.set_text(f"Found {count} USB device{'s' if count != 1 else ''}.", "ok") + else: + self.connection_notice.set_text(f"Could not look for USB devices: {value}", "error") + + def _connect_usb(self) -> None: + device = self._need_device(self.connection_notice) + if device is None: + return + row = self.usb_table.selected_row() + if row < 0 or row >= len(self._usb_serials): + self.connection_notice.set_text("Select a USB device in the table first.", "error") + return + serial = self._usb_serials[row] + self.connection_notice.set_text(f"Connecting through {serial}...", "muted") + self.run(self.service.node.debug_connect_usb(serial), "connect over USB", self._connected("USB")) + + def _connected(self, via: str): + def done(ok: bool, value: Any) -> None: + if ok: + self.connection_notice.set_text(f"Connected over {via}. The route shows in the table above.", "ok") + else: + self.connection_notice.set_text(f"Could not connect over {via}: {value}", "error") + + return done + + # ----- log ---------------------------------------------------------------------------------- + + def _start_log(self) -> None: + device = self._need_device(self.log_notice) + if device is None: + return + self.log_notice.set_text("Starting the log...", "muted") + self.run( + self.service.node.debug_logcat_start(device, self.log_filter.text().strip(), self._log_sink), + "start the device's log", + self._log_started, + ) + + def _log_started(self, ok: bool, value: Any) -> None: + if ok: + self._log_handle = int(value) + self.log_notice.set_text("Reading the log. Stop it when you have what you need.", "ok") + else: + self.log_notice.set_text(f"The log did not start: {value}", "error") + + def _stop_log(self) -> None: + if self._log_handle is None: + return + self.run(self.service.node.debug_stop(self._log_handle), "stop the log") + self._log_handle = None + self.log_notice.set_text("Log stopped.", "muted") + + def _on_log_message(self, message: Dict[str, Any]) -> None: + kind = message.get("t") + if kind == "line": + self.log_view.appendPlainText(str(message.get("text", ""))) + elif kind == "drop": + count = message.get("count", 0) + self.log_view.appendPlainText(f"[{count} line{'s' if count != 1 else ''} skipped: the log came faster than it could be shown]") + elif kind == "error": + self.log_notice.set_text(str(message.get("text", "the log failed")), "error") + + # ----- shell -------------------------------------------------------------------------------- + + def _run_shell(self) -> None: + device = self._need_device(self.shell_notice) + if device is None: + return + command = self.command.text().strip() + if not command: + self.shell_notice.set_text("Type a command first.", "error") + return + self.shell_notice.set_text("Running. If the device's user is asked, accept the request on the device or in Requests below.", "muted") + self.run( + self.service.node.debug_shell(device, command, float(self.shell_timeout.value())), + "run a command on the device", + self._shell_done, + ) + + def _shell_done(self, ok: bool, value: Any) -> None: + if not ok: + self.shell_notice.set_text(f"The command did not run: {value}", "error") + return + out = _text(value.get("stdout", b"")) + err = _text(value.get("stderr", b"")) + self.shell_output.setPlainText(out + (("\n--- stderr ---\n" + err) if err else "")) + code = value.get("code") + finished = f"exit code {code}" if code is not None else "no exit code" + reason = value.get("reason") or "finished" + self.shell_notice.set_text(f"Finished: {finished} ({reason}).", "ok" if code == 0 else "muted") + + # ----- forwarding and operations ------------------------------------------------------------ + + def _start_forward(self) -> None: + device = self._need_device(self.forward_notice) + if device is None: + return + self.run( + self.service.node.debug_forward_start(device, self.local_port.value(), self.device_port.value()), + "start a port forward", + self._forward_started, + ) + + def _forward_started(self, ok: bool, value: Any) -> None: + if ok: + self.forward_notice.set_text("Forwarding started. Its address and state are in Operations below.", "ok") + else: + self.forward_notice.set_text(f"Forwarding did not start: {value}", "error") + + def _stop_selected(self) -> None: + row = self.streams.selected_row() + if row < 0 or row >= len(self._stream_handles): + self.operations_notice.set_text("Select an operation in the table first.", "error") + return + self.run(self.service.node.debug_stop(self._stream_handles[row]), "stop a debug operation", self._stopped) + + def _stopped(self, ok: bool, value: Any) -> None: + if ok: + self.operations_notice.set_text("Stopped.", "ok") + else: + self.operations_notice.set_text(f"Not stopped: {value}", "error") + + # ----- requests from computers -------------------------------------------------------------- + + def _answer(self, accept: bool) -> None: + row = self.requests.selected_row() + if row < 0 or row >= len(self._request_ids): + self.requests_notice.set_text("Select a request in the table first.", "error") + return + request_id = self._request_ids[row] + node = self.service.node + if accept: + self.run(node.accept_request(request_id), "accept a debug request", self._answered(True)) + else: + self.run(node.refuse_request(request_id), "refuse a debug request", self._answered(False)) + + def _answered(self, accepted: bool): + def done(ok: bool, value: Any) -> None: + if ok: + self.requests_notice.set_text("Accepted." if accepted else "Refused.", "ok") + else: + self.requests_notice.set_text(f"Not done: {value}", "error") + + return done diff --git a/gui/transferd_gui/ui/pages/settings.py b/gui/transferd_gui/ui/pages/settings.py index a0ac570..3c1ed11 100644 --- a/gui/transferd_gui/ui/pages/settings.py +++ b/gui/transferd_gui/ui/pages/settings.py @@ -11,6 +11,7 @@ QFileDialog, QFormLayout, QHBoxLayout, + QLabel, QLineEdit, QPushButton, QSpinBox, @@ -18,10 +19,14 @@ ) from transferd_gui.backend import capabilities -from transferd_gui.model.settings import THEMES, Settings, SettingsError +from transferd_gui.debug.policy import MODES +from transferd_gui.model.settings import DEBUG_TRANSPORTS, THEMES, Settings, SettingsError from transferd_gui.ui.pages.base import Page +from transferd_gui.ui.pages.debug import TRANSPORT_LABELS from transferd_gui.ui.widgets import ActionRow, Banner, Card, Notice +MODE_LABELS = {"allow": "Allow", "ask": "Ask the device's user", "deny": "Deny"} + class SettingsPage(Page): key = "settings" @@ -93,6 +98,109 @@ def build(self) -> None: timing.body.addLayout(form2) self.content.addWidget(timing) + debugging = Card("Debugging: what a listed computer may do with this device") + debugging.body.addWidget(QLabel( + "Off until you turn it on. Only the computers listed here can debug this device. For each kind of operation, " + "allow it, ask this device's user each time, or deny it." + )) + device_form = QFormLayout() + self.debug_enabled = QCheckBox("Let listed computers debug this device") + self.debug_clients = QLineEdit() + self.debug_clients.setPlaceholderText("computer node ids, separated by commas (64 hex characters each)") + self.mode_boxes: Dict[str, QComboBox] = {} + for op, label in ( + ("info", "Device information"), + ("logcat", "Log"), + ("shell", "Commands"), + ("forward", "Port forwarding"), + ): + box = QComboBox() + for mode in MODES: + box.addItem(MODE_LABELS[mode], mode) + self.mode_boxes[op] = box + device_form.addRow(label, box) + self.debug_forward_ports = QLineEdit() + self.debug_forward_ports.setPlaceholderText("ports computers may forward to, e.g. 8080, 5555") + self.debug_log_command = QLineEdit() + self.debug_log_command.setPlaceholderText("command that prints the log, e.g. logcat -v time") + self.debug_shell_timeout = QDoubleSpinBox() + self.debug_shell_timeout.setRange(1.0, 600.0) + self.debug_shell_timeout.setSuffix(" s") + self.debug_shell_output = QSpinBox() + self.debug_shell_output.setRange(16, 16384) + self.debug_shell_output.setSuffix(" KiB") + self.debug_streams = QSpinBox() + self.debug_streams.setRange(1, 64) + device_form.addRow("", self.debug_enabled) + device_form.addRow("Listed computers", self.debug_clients) + device_form.addRow("Forward ports", self.debug_forward_ports) + device_form.addRow("Log command", self.debug_log_command) + device_form.addRow("Command time limit", self.debug_shell_timeout) + device_form.addRow("Command output kept", self.debug_shell_output) + device_form.addRow("Operations open per computer", self.debug_streams) + debugging.body.addLayout(device_form) + self.content.addWidget(debugging) + + this_computer = Card("Debugging from this computer") + this_form = QFormLayout() + self.debug_device_id = QLineEdit() + self.debug_device_id.setPlaceholderText("node id of the device to debug (64 hex characters)") + self.debug_transport = QComboBox() + for transport in DEBUG_TRANSPORTS: + self.debug_transport.addItem(TRANSPORT_LABELS[transport], transport) + self.debug_wifi = QLineEdit() + self.debug_wifi.setPlaceholderText("device address for Wi-Fi, host:port") + self.usb_adb = QLineEdit() + self.usb_adb.setPlaceholderText("adb") + self.usb_port = QSpinBox() + self.usb_port.setRange(0, 65535) + self.usb_port.setSpecialValueText("not set") + self.usb_port.setToolTip("The port the device's Transferd node listens on, as the phone sees it.") + this_form.addRow("Device", self.debug_device_id) + this_form.addRow("Transport", self.debug_transport) + this_form.addRow("Wi-Fi address", self.debug_wifi) + this_form.addRow("adb program", self.usb_adb) + this_form.addRow("Device port (USB)", self.usb_port) + this_computer.body.addLayout(this_form) + self.content.addWidget(this_computer) + + wormhole = Card("Wormhole: send a file or text with a code") + wormhole_form = QFormLayout() + self.wormhole_mailbox = QLineEdit() + self.wormhole_mailbox.setPlaceholderText("wss://mailbox.example.net:4470#fingerprint") + self.wormhole_mailbox.setToolTip( + "The mailboxes a wormhole meets on, tried in order and separated by commas. wss:// reaches another computer; " + "the #fingerprint after it pins that computer's certificate. ws://127.0.0.1 is this computer only. " + "Empty uses this computer's own mailbox, when it is hosting one." + ) + self.wormhole_host = QCheckBox("Host a mailbox on this computer") + self.wormhole_host.setToolTip("Nothing listens until this is on. The mailbox sees nameplates and timing, never a code, key or file.") + self.wormhole_host_port = QSpinBox() + self.wormhole_host_port.setRange(1, 65535) + self.wormhole_host_port.setToolTip("The port the hosted mailbox listens on.") + self.wormhole_host_network = QCheckBox("Let other computers reach it, encrypted and pinned to this computer") + self.wormhole_host_network.setToolTip( + "Off: only this computer can use the hosted mailbox. On: it listens on the network, over wss:// with its own " + "certificate. Other computers pin that certificate with the share line from the Wormhole screen." + ) + self.wormhole_streams = QSpinBox() + self.wormhole_streams.setRange(1, 8) + self.wormhole_streams.setToolTip("How many parallel streams a file is spread over on the overlay.") + wormhole_form.addRow("Mailboxes", self.wormhole_mailbox) + wormhole_form.addRow("", self.wormhole_host) + wormhole_form.addRow("Hosted mailbox port", self.wormhole_host_port) + wormhole_form.addRow("", self.wormhole_host_network) + wormhole_form.addRow("Streams per file", self.wormhole_streams) + wormhole.body.addLayout(wormhole_form) + wormhole.body.addWidget( + Notice( + "With no mailbox listed, wormholes on this computer meet on its own hosted mailbox. The relay and the " + "download folder above are used for wormholes too.", + "muted", + ) + ) + self.content.addWidget(wormhole) + unavailable = Card("Options this build cannot change") unavailable.body.addWidget(Banner(capabilities.reason(capabilities.CUSTOM_RELAY_TOKEN))) unavailable.body.addWidget(Banner(capabilities.reason(capabilities.RELAY_UDP_PORT))) @@ -136,6 +244,29 @@ def _fill(self, settings: Settings) -> None: self.theme.setCurrentText(settings.theme) self.log_size.setValue(settings.event_log_size) self.window_s.setValue(settings.telemetry_window_s) + self.debug_enabled.setChecked(settings.debug_enabled) + self.debug_clients.setText(settings.debug_clients) + for op, box in self.mode_boxes.items(): + self._set_combo(box, getattr(settings, f"debug_{op}_mode")) + self.debug_forward_ports.setText(settings.debug_forward_ports) + self.debug_log_command.setText(settings.debug_log_command) + self.debug_shell_timeout.setValue(settings.debug_shell_timeout_s) + self.debug_shell_output.setValue(settings.debug_shell_output_kib) + self.debug_streams.setValue(settings.debug_streams_per_client) + self.debug_device_id.setText(settings.debug_device_id) + self._set_combo(self.debug_transport, settings.debug_transport) + self.debug_wifi.setText(settings.debug_wifi_address) + self.usb_adb.setText(settings.usb_adb_path) + self.usb_port.setValue(settings.usb_device_port) + self.wormhole_mailbox.setText(settings.wormhole_mailbox) + self.wormhole_host.setChecked(settings.wormhole_host) + self.wormhole_host_port.setValue(settings.wormhole_host_port) + self.wormhole_host_network.setChecked(settings.wormhole_host_network) + self.wormhole_streams.setValue(settings.wormhole_streams) + + @staticmethod + def _set_combo(box: QComboBox, value: str) -> None: + box.setCurrentIndex(max(box.findData(value), 0)) def _collect(self) -> Dict[str, Any]: return { @@ -153,6 +284,27 @@ def _collect(self) -> Dict[str, Any]: "theme": self.theme.currentText(), "event_log_size": self.log_size.value(), "telemetry_window_s": self.window_s.value(), + "debug_enabled": self.debug_enabled.isChecked(), + "debug_clients": self.debug_clients.text().strip(), + "debug_info_mode": self.mode_boxes["info"].currentData(), + "debug_logcat_mode": self.mode_boxes["logcat"].currentData(), + "debug_shell_mode": self.mode_boxes["shell"].currentData(), + "debug_forward_mode": self.mode_boxes["forward"].currentData(), + "debug_forward_ports": self.debug_forward_ports.text().strip(), + "debug_log_command": self.debug_log_command.text().strip(), + "debug_shell_timeout_s": float(self.debug_shell_timeout.value()), + "debug_shell_output_kib": self.debug_shell_output.value(), + "debug_streams_per_client": self.debug_streams.value(), + "debug_device_id": self.debug_device_id.text().strip().lower(), + "debug_transport": self.debug_transport.currentData(), + "debug_wifi_address": self.debug_wifi.text().strip(), + "usb_adb_path": self.usb_adb.text().strip(), + "usb_device_port": self.usb_port.value(), + "wormhole_mailbox": self.wormhole_mailbox.text().strip(), + "wormhole_host": self.wormhole_host.isChecked(), + "wormhole_host_port": self.wormhole_host_port.value(), + "wormhole_host_network": self.wormhole_host_network.isChecked(), + "wormhole_streams": self.wormhole_streams.value(), } def _save(self) -> None: diff --git a/gui/transferd_gui/ui/pages/wormhole.py b/gui/transferd_gui/ui/pages/wormhole.py new file mode 100644 index 0000000..55e7759 --- /dev/null +++ b/gui/transferd_gui/ui/pages/wormhole.py @@ -0,0 +1,411 @@ +"""The Wormhole screen: send a file, a folder or a text with a short code, or type a code and receive what is offered. + +Nothing is sent until the other computer has typed the code and the receiving user has accepted the offer. The code is +shown as soon as the mailbox has it, and stays on screen until the attempt ends or is cancelled. + +Each attempt has a generation number. Cancelling bumps it, so a result or status line that arrives late from a cancelled +attempt is ignored, and a sender or receiver that finished after its attempt was cancelled is closed instead of shown. +""" + +from __future__ import annotations + +from typing import Any, Optional + +from PySide6.QtCore import Qt +from PySide6.QtGui import QGuiApplication +from PySide6.QtWidgets import ( + QFileDialog, + QFormLayout, + QLabel, + QLineEdit, + QPlainTextEdit, + QPushButton, +) + +from transferd_gui.backend.wormhole import WormholeService +from transferd_gui.model.eventlog import LogEntry +from transferd_gui.model.settings import Settings +from transferd_gui.ui.pages.base import Page +from transferd_gui.ui.widgets import ActionRow, Card, Notice +from transferd_gui.wormhole.addresses import display_fingerprint +from transferd_gui.wormhole.session import ReceiveResult, Receiver, SendResult, Sender + + +def describe_offer(receiver: Receiver) -> str: + offer = receiver.offer_received + if offer is None: + return "" + if offer.kind == "text": + return f"A text of {offer.size} bytes is offered." + if offer.kind == "directory": + return f"A folder named {offer.name} ({offer.entries} entries, {offer.size} bytes) is offered." + return f"A file named {offer.name} ({offer.size} bytes) is offered." + + +class WormholePage(Page): + key = "wormhole" + title = "Wormhole" + explainer = ( + "Send a file, a folder or a text with a short code, or type the code someone gave you. The mailbox server, the relay " + "and the download folder come from Settings. Nothing is sent until the receiving side accepts the offer." + ) + + def build(self) -> None: + self.wormhole = WormholeService(self.service) + self._sender: Optional[Sender] = None + self._send_future: Any = None + self._send_gen = 0 + self._receiver: Optional[Receiver] = None + self._receive_future: Any = None + self._receive_gen = 0 + + self.setup_notice = Notice() + self.content.addWidget(self.setup_notice) + + mailbox = Card("Mailbox") + self.meeting_notice = Notice("", "muted") + self.host_notice = Notice("", "muted") + self.share_edit = QLineEdit() + self.share_edit.setReadOnly(True) + self.share_edit.setToolTip("Paste this into the other computer's mailbox list in Settings (Wormhole).") + self.copy_share_button = QPushButton("Copy share line") + self.copy_share_button.clicked.connect(self._copy_share) + self.share_hint = Notice( + "Other computers add this line to their mailbox list in Settings (Wormhole). It carries this computer's " + "fingerprint, so they reach this mailbox and no other.", + "muted", + ) + self._share_widgets = (self.share_edit, self.copy_share_button, self.share_hint) + mailbox.body.addWidget(self.meeting_notice) + mailbox.body.addWidget(self.host_notice) + mailbox.body.addWidget(self.share_edit) + mailbox.body.addWidget(ActionRow(self.copy_share_button)) + mailbox.body.addWidget(self.share_hint) + self.content.addWidget(mailbox) + + send = Card("Send") + self.send_file_button = QPushButton("Send a file") + self.send_folder_button = QPushButton("Send a folder") + self.send_file_button.clicked.connect(self._choose_file) + self.send_folder_button.clicked.connect(self._choose_folder) + self.text_input = QPlainTextEdit() + self.text_input.setPlaceholderText("Or type a text to send, then press Send text.") + self.text_input.setMaximumHeight(90) + self.send_text_button = QPushButton("Send text") + self.send_text_button.clicked.connect(self._send_text) + send.body.addWidget(ActionRow(self.send_file_button, self.send_folder_button)) + send.body.addWidget(self.text_input) + send.body.addWidget(ActionRow(self.send_text_button)) + self.code_label = QLabel("") + self.code_label.setObjectName("title") + self.code_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + self.copy_code_button = QPushButton("Copy code") + self.copy_code_button.clicked.connect(self._copy_code) + self.cancel_send_button = QPushButton("Cancel") + self.cancel_send_button.clicked.connect(self._cancel_send) + send.body.addWidget(self.code_label) + send.body.addWidget(ActionRow(self.copy_code_button, self.cancel_send_button)) + self.send_status = Notice("Nothing is being sent.", "muted") + send.body.addWidget(self.send_status) + self.content.addWidget(send) + + receive = Card("Receive") + self.code_input = QLineEdit() + self.code_input.setPlaceholderText("the code, for example 4217-ember-tundra-lattice") + self.look_up_button = QPushButton("Look up the code") + self.look_up_button.clicked.connect(self._look_up) + form = QFormLayout() + form.addRow("Code", self.code_input) + receive.body.addLayout(form) + receive.body.addWidget(ActionRow(self.look_up_button)) + self.offer_label = Notice("", "muted") + self.accept_button = QPushButton("Accept") + self.decline_button = QPushButton("Decline") + self.accept_button.clicked.connect(lambda: self._answer(True)) + self.decline_button.clicked.connect(lambda: self._answer(False)) + receive.body.addWidget(self.offer_label) + receive.body.addWidget(ActionRow(self.accept_button, self.decline_button)) + self.received_text = QPlainTextEdit() + self.received_text.setReadOnly(True) + self.received_text.setMaximumHeight(120) + self.received_text.setVisible(False) + receive.body.addWidget(self.received_text) + self.receive_status = Notice("Nothing is being received.", "muted") + receive.body.addWidget(self.receive_status) + self.stop_receive_button = QPushButton("Stop") + self.stop_receive_button.clicked.connect(self._stop_receive) + receive.body.addWidget(ActionRow(self.stop_receive_button)) + self.content.addWidget(receive) + + self._refresh_availability(self.service.settings) + self._set_offer_buttons(False) + self.cancel_send_button.setEnabled(False) + self.stop_receive_button.setEnabled(False) + + # ----- availability ----------------------------------------------------------------------------- + + def on_settings(self, settings: Settings) -> None: + self._refresh_availability(settings) + + def on_show(self) -> None: + self._refresh_availability(self.service.settings) + + def on_log(self, entry: LogEntry) -> None: + # The hosted mailbox writes to the log when it starts, stops or fails, so its state is read again then. + if entry.source == "mailbox": + self._refresh_availability(self.service.settings) + + def _refresh_availability(self, settings: Settings) -> None: + reason = self.wormhole.problem() + enabled = not reason + if reason: + self.setup_notice.set_text(reason, "error") + else: + self.setup_notice.set_text(f"The mailbox is {self.wormhole.mailbox()}.", "muted") + for widget in ( + self.send_file_button, + self.send_folder_button, + self.send_text_button, + self.text_input, + self.look_up_button, + self.code_input, + ): + widget.setEnabled(enabled) + self._refresh_mailbox_card(settings) + + def _refresh_mailbox_card(self, settings: Settings) -> None: + hosting = self.service.mailbox_host + status = hosting.status() + listed = settings.wormhole_mailbox.strip() + here = hosting.address_here() + if listed: + meeting, tone = f"Wormholes meet on the mailbox list in Settings: {listed}", "muted" + elif here: + meeting, tone = f"Wormholes on this computer meet on its own mailbox: {here}", "muted" + else: + meeting, tone = "No mailbox is set, so wormholes are off. Add one in Settings, or host one on this computer.", "error" + self.meeting_notice.set_text(meeting, tone) + if status.error: + self.host_notice.set_text(status.error, "error") + elif status.running and status.network: + self.host_notice.set_text( + f"Hosting a mailbox on port {status.port}, reachable from other computers. " + f"Its fingerprint: {display_fingerprint(status.fingerprint)}", + "muted", + ) + elif status.running: + self.host_notice.set_text(f"Hosting a mailbox on port {status.port}, for this computer only.", "muted") + elif status.enabled: + self.host_notice.set_text("Starting the hosted mailbox.", "muted") + else: + self.host_notice.set_text("This computer is not hosting a mailbox. Turn hosting on in Settings (Wormhole).", "muted") + share = hosting.share_line() + self.share_edit.setText(share) + for widget in self._share_widgets: + widget.setVisible(bool(share)) + + def _copy_share(self) -> None: + share = self.service.mailbox_host.share_line() + if share: + QGuiApplication.clipboard().setText(share) + + def _set_offer_buttons(self, on: bool) -> None: + self.accept_button.setEnabled(on) + self.decline_button.setEnabled(on) + + # ----- sending ---------------------------------------------------------------------------------- + + def _choose_file(self) -> None: + path, _ = QFileDialog.getOpenFileName(self, "Choose a file to send") + if path: + self.send_file(path) + + def _choose_folder(self) -> None: + path = QFileDialog.getExistingDirectory(self, "Choose a folder to send") + if path: + self.send_folder(path) + + def _send_text(self) -> None: + text = self.text_input.toPlainText() + if not text.strip(): + self.send_status.set_text("Type a text first.", "error") + return + self.send_text(text) + + def send_file(self, path: str) -> None: + self._begin_send("file", path, "Preparing the file") + + def send_folder(self, path: str) -> None: + self._begin_send("folder", path, "Zipping the folder") + + def send_text(self, text: str) -> None: + self._begin_send("text", text, "Preparing the text") + + def _begin_send(self, kind: str, value: str, status: str) -> None: + if self._send_future is not None: + self.send_status.set_text("A send is already in progress. Cancel it first.", "error") + return + self._send_gen += 1 + gen = self._send_gen + self.send_status.set_text(status + "...", "muted") + self.cancel_send_button.setEnabled(True) + future = self.service.run( + self.wormhole.start_send(kind, value, self.bridge.on_ui(lambda text: self._say_send(gen, text))), + "start a wormhole send", + self.bridge.on_ui(lambda ok, result: self._send_started(gen, ok, result)), + ) + if future is None: + self._send_reset("The node is not running, so nothing can be sent.", "error") + return + self._send_future = future + + def _say_send(self, gen: int, text: str) -> None: + if gen == self._send_gen: + self.send_status.set_text(text, "muted") + + def _send_started(self, gen: int, ok: bool, result: Any) -> None: + if gen != self._send_gen: + # Cancelled while the code was being reserved: close the mailbox the sender opened. + if ok: + self.service.run(self.wormhole.abandon(result), "stop a wormhole send") + return + if not ok: + self._send_reset(str(result), "error") + return + self._sender = result + self.code_label.setText(str(result.code)) + self.send_status.set_text("Waiting for the other computer to type this code.", "muted") + self._send_future = self.service.run( + self.wormhole.run_send(result), + "send a wormhole", + self.bridge.on_ui(lambda ok2, value: self._send_finished(gen, ok2, value)), + ) + + def _send_finished(self, gen: int, ok: bool, result: Any) -> None: + if gen != self._send_gen: + return + if not ok: + self._send_reset(str(result), "error") + return + outcome: SendResult = result + if outcome.declined: + detail = f" Reason: {outcome.reason}" if outcome.reason else "" + self._send_reset("Declined by the other computer." + detail, "muted") + else: + self._send_reset("Sent.", "ok") + + def _send_reset(self, text: str, tone: str) -> None: + self._sender = None + self._send_future = None + self.cancel_send_button.setEnabled(False) + self.code_label.setText("") + self.send_status.set_text(text, tone) + + def _cancel_send(self) -> None: + if self._send_future is None: + return + self._send_gen += 1 + # Cancelling ends the attempt on its own: the sender closes its mailbox whether it is reserving a code or sending. + self._send_future.cancel() + self._send_reset("Cancelled. The code no longer works.", "muted") + + def _copy_code(self) -> None: + if self._sender is not None: + QGuiApplication.clipboard().setText(str(self._sender.code)) + self.send_status.set_text("The code is on the clipboard.", "muted") + + # ----- receiving -------------------------------------------------------------------------------- + + def _look_up(self) -> None: + if self._receive_future is not None or self._receiver is not None: + self.receive_status.set_text("A receive is already in progress. Stop it first.", "error") + return + code = self.code_input.text().strip() + if not code: + self.receive_status.set_text("Type the code first.", "error") + return + self._receive_gen += 1 + gen = self._receive_gen + self._set_offer_buttons(False) + self.received_text.setVisible(False) + self.receive_status.set_text("Looking up the code...", "muted") + self.stop_receive_button.setEnabled(True) + future = self.service.run( + self.wormhole.open_receive(code, self.bridge.on_ui(lambda text: self._say_receive(gen, text))), + "look up a wormhole code", + self.bridge.on_ui(lambda ok, result: self._looked_up(gen, ok, result)), + ) + if future is None: + self._receive_reset("The node is not running, so the code cannot be used.", "error") + return + self._receive_future = future + + def _say_receive(self, gen: int, text: str) -> None: + if gen == self._receive_gen: + self.receive_status.set_text(text, "muted") + + def _looked_up(self, gen: int, ok: bool, result: Any) -> None: + if gen != self._receive_gen: + if ok: + self.service.run(self.wormhole.abandon(result), "stop a wormhole receive") + return + self._receive_future = None + if not ok: + self._receive_reset(str(result), "error") + return + self._receiver = result + self.offer_label.set_text(describe_offer(result), "ok") + self._set_offer_buttons(True) + self.receive_status.set_text("Accept to receive it, or decline. Stop declines it and closes the code.", "muted") + + def _answer(self, accept: bool) -> None: + if self._receiver is None or self._receive_future is not None: + return + gen = self._receive_gen + self._set_offer_buttons(False) + self.receive_status.set_text("Receiving..." if accept else "Declining...", "muted") + reason = "" if accept else "the receiving user declined" + self._receive_future = self.service.run( + self.wormhole.finish_receive(self._receiver, accept, reason), + "receive a wormhole", + self.bridge.on_ui(lambda ok, result: self._received(gen, ok, result)), + ) + if self._receive_future is None: + self._receive_reset("The node is not running.", "error") + + def _received(self, gen: int, ok: bool, result: Any) -> None: + if gen != self._receive_gen: + return + self._receive_future = None + if not ok: + self._receive_reset(str(result), "error") + return + outcome: ReceiveResult = result + if outcome.kind == "declined": + self._receive_reset("Declined.", "muted") + elif outcome.kind == "text": + self.received_text.setPlainText(outcome.text) + self.received_text.setVisible(True) + self._receive_reset("Received a text.", "ok") + else: + self._receive_reset(f"Saved to {outcome.path}", "ok") + + def _receive_reset(self, text: str, tone: str) -> None: + self._receiver = None + self._receive_future = None + self._set_offer_buttons(False) + self.stop_receive_button.setEnabled(False) + self.offer_label.set_text("", "muted") + self.receive_status.set_text(text, tone) + + def _stop_receive(self) -> None: + if self._receive_future is not None: + # Looking up or receiving: cancelling ends the attempt, and the other side is told it did not finish. + self._receive_gen += 1 + self._receive_future.cancel() + self._receive_reset("Stopped.", "muted") + elif self._receiver is not None: + # Waiting on the offer: decline it so the sender is told, and close the code. + self._receive_gen += 1 + self.service.run(self.wormhole.abandon(self._receiver), "stop a wormhole receive") + self._receive_reset("Stopped. The offer was declined.", "muted") diff --git a/gui/transferd_gui/wormhole/__init__.py b/gui/transferd_gui/wormhole/__init__.py new file mode 100644 index 0000000..ca3f4dc --- /dev/null +++ b/gui/transferd_gui/wormhole/__init__.py @@ -0,0 +1,11 @@ +"""Transferd Wormhole: send a file, a folder or a text with a short code. See `gui\\docs\\WORMHOLE.md` for the design. + +Importing this package puts the repository's `python` folder on `sys.path`, so `import transferd` works from here on, as it +does in the rest of the GUI. +""" + +from __future__ import annotations + +from transferd_gui.paths import ensure_library_on_path + +ensure_library_on_path() diff --git a/gui/transferd_gui/wormhole/addresses.py b/gui/transferd_gui/wormhole/addresses.py new file mode 100644 index 0000000..3b2ba1b --- /dev/null +++ b/gui/transferd_gui/wormhole/addresses.py @@ -0,0 +1,114 @@ +"""The mailbox addresses a wormhole may meet on, and the list Settings holds. Text only: no network and no TLS here, so Settings +can check a value without loading either. + +An address is `ws://` (this computer only) or `wss://`, with an optional pin after a `#`. The pin is the SHA-256 fingerprint of +the mailbox's certificate, as the computer hosting the mailbox shows it: + + wss://mailbox.example.net:4470#9f2c... a mailbox on the network, held to its pinned certificate + wss://mailbox.example.net no pin: the system's certificates are checked; the port is 4470 + ws://127.0.0.1:4470 this computer only, never reached over the network + +The `#` part is never sent to a server. The setting is a comma-separated list. The first address is tried first, and the +next only when the first cannot be reached. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Tuple +from urllib.parse import urlsplit + +DEFAULT_PORT = 4470 +MAX_MAILBOXES = 4 +MAX_ADDRESS_LENGTH = 200 +LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) +_FINGERPRINT = re.compile(r"[0-9a-f]{64}") + + +@dataclass(frozen=True) +class MailboxAddress: + scheme: str # "ws" or "wss" + host: str + port: int + pin: str = "" # lower-case SHA-256 of the certificate; "" means the system's certificates are checked + + @property + def loopback(self) -> bool: + return self.host in LOOPBACK_HOSTS + + @property + def url(self) -> str: + host = f"[{self.host}]" if ":" in self.host else self.host + return f"{self.scheme}://{host}:{self.port}" + + def text(self) -> str: + """The address as it is written in Settings, pin included.""" + return f"{self.url}#{self.pin}" if self.pin else self.url + + +def normalise_fingerprint(text: str) -> str: + """A fingerprint as lower-case hex. Spaces, colons and dashes are allowed, since people copy them that way.""" + cleaned = re.sub(r"[\s:\-]", "", text).lower() + if not _FINGERPRINT.fullmatch(cleaned): + raise ValueError("a fingerprint is 64 hexadecimal characters, as the computer hosting the mailbox shows it") + return cleaned + + +def display_fingerprint(pin: str) -> str: + """A fingerprint in groups of eight, easy to read out and compare.""" + return " ".join(pin[i : i + 8] for i in range(0, len(pin), 8)) + + +def parse_address(text: str) -> MailboxAddress: + """One address. Raises ValueError with a message a user can act on.""" + value = text.strip() + if not value: + raise ValueError("an address is empty") + if len(value) > MAX_ADDRESS_LENGTH: + raise ValueError(f"an address is at most {MAX_ADDRESS_LENGTH} characters") + if any(c.isspace() for c in value): + raise ValueError(f"an address has spaces in it: '{value}'") + try: + parts = urlsplit(value) + port = parts.port + except ValueError as exc: + raise ValueError(f"'{value}' does not end in a port from 1 to 65535") from exc + scheme = parts.scheme.lower() + if scheme not in ("ws", "wss"): + raise ValueError(f"'{value}' must start with wss:// (another computer) or ws:// (this computer only)") + host = parts.hostname + if not host: + raise ValueError(f"'{value}' needs a host name or an address") + if parts.username or parts.password: + raise ValueError(f"'{value}' has a user name or password; a mailbox address has neither") + if parts.path not in ("", "/") or parts.query: + raise ValueError(f"'{value}' is only a host and a port, with an optional #fingerprint after them") + if port is not None and not 1 <= port <= 65535: + raise ValueError(f"'{value}' has a port outside 1 to 65535") + pin = "" + if parts.fragment: + if scheme == "ws": + raise ValueError("a fingerprint after # is for wss:// addresses; ws:// is not encrypted and has none") + pin = normalise_fingerprint(parts.fragment) + if scheme == "ws" and host not in LOOPBACK_HOSTS: + raise ValueError(f"ws:// reaches only this computer; use wss:// for '{host}'") + return MailboxAddress(scheme, host, port or DEFAULT_PORT, pin) + + +def parse_list(text: str) -> Tuple[MailboxAddress, ...]: + """The comma-separated list in Settings, in the order given. An empty text is no list. Raises ValueError.""" + if not text.strip(): + return () + entries = text.split(",") + if len(entries) > MAX_MAILBOXES: + raise ValueError(f"at most {MAX_MAILBOXES} mailboxes, tried in the order given") + addresses = [] + for index, entry in enumerate(entries, start=1): + if not entry.strip(): + raise ValueError(f"entry {index} of the list is empty; separate addresses with commas and nothing else") + address = parse_address(entry) + if address in addresses: + raise ValueError(f"'{address.url}' is listed twice") + addresses.append(address) + return tuple(addresses) diff --git a/gui/transferd_gui/wormhole/codes.py b/gui/transferd_gui/wormhole/codes.py new file mode 100644 index 0000000..3cf1d07 --- /dev/null +++ b/gui/transferd_gui/wormhole/codes.py @@ -0,0 +1,93 @@ +"""Wormhole codes: a nameplate and three PGP words, such as `4217-ember-tundra-lattice`. + +The nameplate is a decimal number the mailbox allocates. The three words spell three random bytes, which is the secret: 24 +bits. The word at position `i` comes from the even list when `i` is even and the odd list when it is odd, so a dropped or +swapped word is seen when the code is read back. + +Reading a code is forgiving about case, spaces and underscores, and strict about everything else. +""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from typing import Callable, Tuple + +from transferd_gui.wormhole.errors import CodeError +from transferd_gui.wormhole.wordlist import EVEN_WORDS, LOOKUP, ODD_WORDS + +NAMEPLATE_MIN = 1 +NAMEPLATE_MAX = 65535 +#: The number of words after the nameplate. Each word carries 8 bits of the secret. +WORD_COUNT = 3 +_NUMBER = re.compile(r"[0-9]+") +_SEPARATORS = re.compile(r"[\s_\-]+") + + +@dataclass(frozen=True) +class Code: + """A code: its nameplate and its secret bytes. The words are derived from the secret.""" + + nameplate: int + secret: bytes + + def __post_init__(self) -> None: + if not NAMEPLATE_MIN <= self.nameplate <= NAMEPLATE_MAX: + raise CodeError(f"the number must be from {NAMEPLATE_MIN} to {NAMEPLATE_MAX}") + if len(self.secret) != WORD_COUNT: + raise CodeError(f"a code has {WORD_COUNT} secret bytes, not {len(self.secret)}") + + @property + def words(self) -> Tuple[str, ...]: + return tuple(word_for(position, byte) for position, byte in enumerate(self.secret)) + + def __str__(self) -> str: + return "-".join([str(self.nameplate), *self.words]) + + def password(self) -> bytes: + """What the key exchange is run with. It includes the nameplate, so the mailbox cannot change it unnoticed.""" + return str(self).encode("ascii") + + +def word_for(position: int, byte: int) -> str: + """The word that spells `byte` at `position`: even list for even positions, odd list for odd ones.""" + if not 0 <= byte <= 255: + raise CodeError("a secret byte must be from 0 to 255") + return ODD_WORDS[byte] if position % 2 else EVEN_WORDS[byte] + + +def generate(nameplate: int, random_bytes: Callable[[int], bytes] = os.urandom) -> Code: + """A new code for a nameplate the mailbox has allocated. `random_bytes` is replaceable so tests can fix the code.""" + secret = random_bytes(WORD_COUNT) + return Code(nameplate, bytes(secret)) + + +def normalise(text: str) -> str: + """Case, spaces and underscores are not significant. Runs of separators become one `-`.""" + return _SEPARATORS.sub("-", text.strip().lower()).strip("-") + + +def parse(text: str) -> Code: + """Read a code back. Raises `CodeError` with the reason when it does not check out.""" + if not isinstance(text, str): + raise CodeError("a code is text") + parts = normalise(text).split("-") + if len(parts) != WORD_COUNT + 1 or parts[0] == "": + raise CodeError(f"a code is a number and {WORD_COUNT} words, such as 4217-ember-tundra-lattice") + number, words = parts[0], parts[1:] + if not _NUMBER.fullmatch(number): + raise CodeError("the code starts with a number, the nameplate") + nameplate = int(number) + if not NAMEPLATE_MIN <= nameplate <= NAMEPLATE_MAX: + raise CodeError(f"the number must be from {NAMEPLATE_MIN} to {NAMEPLATE_MAX}") + secret = bytearray() + for position, word in enumerate(words): + entry = LOOKUP.get(word) + if entry is None: + raise CodeError(f"'{word}' is not a word in the code list") + byte, parity = entry + if parity != position % 2: + raise CodeError(f"word {position + 1} is in the wrong place; a word may be missing or out of order") + secret.append(byte) + return Code(nameplate, bytes(secret)) diff --git a/gui/transferd_gui/wormhole/endpoint.py b/gui/transferd_gui/wormhole/endpoint.py new file mode 100644 index 0000000..432bc73 --- /dev/null +++ b/gui/transferd_gui/wormhole/endpoint.py @@ -0,0 +1,564 @@ +"""The overlay transit: a wormhole's file moves over Transferd's overlay, on a direct TCP route, through a relay, or both. + +The sender dials; the receiver serves. Both sides have an ephemeral identity for the attempt, which was sent under the +phase keys, so every connection is checked against the identity the code named. Routes that come up become links of one +overlay session. A route that is cut is handled by the overlay: what was in flight on it is sent again on another route. + +Over the session, the sender opens two kinds of stream: + + wormhole.control one JSON header line, then the receiver writes `{"have": n}` lines back (its progress) + wormhole.data frames: offset (8 bytes, big-endian), length (4 bytes), then the bytes of one chunk + +Chunk `i` of `CHUNK` bytes goes on data stream `i % streams`. The sender stays within `WINDOW_BYTES` of what the receiver has +reported, so a large file is never queued in memory. A data stream ends with the sender's FIN. +""" + +from __future__ import annotations + +import asyncio +import ipaddress +import json +import socket +import struct +from dataclasses import dataclass +from pathlib import Path +from typing import Callable, Dict, List, Optional, Tuple + +from transferd.frames import ServiceInfo +from transferd.handshake import handshake_initiator, handshake_responder +from transferd.identity import HybridIdentity, relay_token_for +from transferd.link import Link, RouteKind, TcpLink +from transferd.overlay import OverlaySession, SessionSetup, spawn +from transferd.relay_hub import RelayHub + +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.errors import TimedOut, TransferError +from transferd_gui.wormhole.transfer import CHUNK + +CONTROL = "wormhole.control" +DATA = "wormhole.data" +STREAMS_DEFAULT = 4 +STREAMS_MAX = 8 +WINDOW_BYTES = 8 * 1024 * 1024 +PROGRESS_BYTES = 1024 * 1024 +IDLE_TIMEOUT_S = 120.0 +DIAL_TIMEOUT_S = 10.0 +READY_TIMEOUT_S = 15.0 +ACCEPT_TIMEOUT_S = 300.0 +FRAME = struct.Struct(">QI") +_PROGRESS_LINE = 1 << 16 + + +@dataclass +class _Receive: + """The receiver's state for one transfer: the header once it is read, the file, and which chunks have arrived.""" + + header_ready: asyncio.Event + done: asyncio.Event + have: set + have_bytes: int = 0 + reported: int = 0 + size: int = 0 + streams_expected: int = 0 + streams_ended: int = 0 + file: Optional[object] = None + activity: float = 0.0 + error: Optional[BaseException] = None + + +def _private(host: str) -> bool: + try: + return ipaddress.ip_address(host).is_private + except ValueError: + return False + + +def _parse_addr(text: str) -> Tuple[str, int]: + host, sep, port = text.rpartition(":") + if not sep or not host or not port.isdigit() or not 0 < int(port) < 65536: + raise TransferError(f"a relay address is host:port, not '{text}'") + return host, int(port) + + +class OverlayTransit: + """One attempt's transit. Create it, `open` it, and let the session drive it. `close` when the attempt ends.""" + + def __init__( + self, + *, + name: str = "", + relay: str = "", + listen_host: str = "0.0.0.0", + listen_port: int = 0, + advertise: Optional[List[str]] = None, + streams: int = STREAMS_DEFAULT, + dial_timeout: float = DIAL_TIMEOUT_S, + ready_timeout: float = READY_TIMEOUT_S, + accept_timeout: float = ACCEPT_TIMEOUT_S, + idle_timeout: float = IDLE_TIMEOUT_S, + on_state: Optional[Callable[[str], None]] = None, + ) -> None: + self.identity = HybridIdentity.generate(name) + self._name = name + self._relay = relay.strip() + self._listen = (listen_host, listen_port) + self._advertise = advertise + self._streams = max(1, min(STREAMS_MAX, int(streams))) + self._dial_timeout = dial_timeout + self._ready_timeout = ready_timeout + self._accept_timeout = accept_timeout + self._idle_timeout = idle_timeout + self._say = on_state or (lambda text: None) + self._server: Optional[asyncio.AbstractServer] = None + self._port = 0 + self._hub: Optional[RelayHub] = None + self._hubs: Dict[str, RelayHub] = {} + self._peer: Optional[P.PeerIdentity] = None + self._inbound: asyncio.Queue = asyncio.Queue() + self._session: Optional[OverlaySession] = None + self._events: Optional[asyncio.Queue] = None + self._streams_q: asyncio.Queue = asyncio.Queue() + self._down = asyncio.Event() + self._tasks: List[asyncio.Task] = [] + self._sent = 0 + self._have_reported = 0 + self._progress = asyncio.Event() + self.routes_seen: List[str] = [] + + # ----- what this side offers the other ---------------------------------------------------------- + + def local_identity(self) -> P.PeerIdentity: + hints = tuple(P.Hint(host, self._port) for host in self._local_hosts()) if self._server is not None else () + return P.PeerIdentity(self.identity.node_id, self.identity.public_key, self._name, self._relay, hints) + + def expect_peer(self, peer: P.PeerIdentity) -> None: + self._peer = peer + + def _local_hosts(self) -> List[str]: + if self._advertise is not None: + return list(self._advertise)[:P.HINTS_MAX] + hosts = set() + try: + for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): + address = info[4][0] + if not ipaddress.ip_address(address).is_loopback: + hosts.add(address) + except OSError: + pass + return sorted(hosts)[: P.HINTS_MAX] + + def _admit(self, node_id: str, public_key: bytes) -> bool: + """Only the peer named in the identity phase may connect, direct or through the relay.""" + peer = self._peer + return peer is not None and node_id == peer.node_id and public_key == peer.public_key + + # ----- listening and relays ---------------------------------------------------------------------- + + async def open(self) -> None: + if self._server is None: + self._server = await asyncio.start_server(self._on_tcp, self._listen[0], self._listen[1]) + self._port = int(self._server.sockets[0].getsockname()[1]) + if self._relay and self._hub is None: + self._hub = await self._make_hub(self._relay) + + async def _make_hub(self, relay_addr: str) -> RelayHub: + hub = RelayHub( + _parse_addr(relay_addr), + relay_token_for(self.identity.node_id), + self.identity, + admit=self._admit, + on_adopt=self._on_adopt, + ) + await hub.start() + return hub + + async def _hub_for(self, relay_addr: str) -> RelayHub: + if self._hub is not None and relay_addr == self._relay: + return self._hub + if relay_addr not in self._hubs: + self._hubs[relay_addr] = await self._make_hub(relay_addr) + return self._hubs[relay_addr] + + async def _on_tcp(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + """A direct connection: the hybrid handshake, then the identity check, then a link for the session.""" + try: + result = await asyncio.wait_for(handshake_responder(reader, writer, self.identity), self._dial_timeout) + if not self._admit(result.peer_node_id, result.peer_hybrid_public_key): + writer.close() + return + peername = writer.get_extra_info("peername") or ("", 0) + kind = RouteKind.LAN if _private(str(peername[0])) else RouteKind.DIRECT + link = TcpLink(reader, writer, result.keys, kind=kind, describe=f"direct {peername[0]}") + link.start() + await self._inbound.put(link) + except Exception: + writer.close() + + async def _on_adopt(self, link: Link, peer_id: str, peer_key: bytes, _sender: bytes) -> None: + """A handshake that came through the relay from the named peer. The link is already started.""" + if self._admit(peer_id, peer_key): + await self._inbound.put(link) + + # ----- dialling ---------------------------------------------------------------------------------- + + async def _dial_hint(self, peer: P.PeerIdentity, hint: P.Hint) -> Link: + reader, writer = await asyncio.open_connection(hint.host, hint.port) + try: + result = await handshake_initiator(reader, writer, self.identity, expect_node_id=peer.node_id) + if result.peer_hybrid_public_key != peer.public_key: + raise TransferError("the computer at that address is not the one the code named") + except BaseException: + writer.close() + raise + kind = RouteKind.LAN if _private(hint.host) else RouteKind.DIRECT + link = TcpLink(reader, writer, result.keys, kind=kind, describe=f"direct {hint.host}:{hint.port}") + link.start() + return link + + async def _dial_relay(self, peer: P.PeerIdentity) -> Link: + hub = await self._hub_for(peer.relay) + token = relay_token_for(peer.node_id) + keys, peer_key = await hub.handshake(peer.node_id, token) + if peer_key != peer.public_key: + raise TransferError("the relay reached a computer other than the one the code named") + return hub.link(token, keys) + + async def _dial(self, peer: P.PeerIdentity) -> List[Link]: + """Every route at once: each direct address, and the relay if the peer is on one. Returns the links that came up.""" + attempts = [asyncio.wait_for(self._dial_hint(peer, hint), self._dial_timeout) for hint in peer.hints] + if peer.relay: + attempts.append(asyncio.wait_for(self._dial_relay(peer), self._dial_timeout)) + if not attempts: + raise TransferError("the other computer gave no way to reach it") + self._say("Connecting") + results = await asyncio.gather(*attempts, return_exceptions=True) + links = [r for r in results if isinstance(r, Link)] + if not links: + raise TransferError("the other computer could not be reached by any route") + return links + + # ----- the session ------------------------------------------------------------------------------- + + async def _start_session(self, peer: P.PeerIdentity, links: List[Link]) -> OverlaySession: + self._events = asyncio.Queue() + setup = SessionSetup( + peer_node_id=peer.node_id, + peer_name=peer.name, + identity=self.identity, + services=[ + ServiceInfo(CONTROL, "the header and progress of a wormhole transfer"), + ServiceInfo(DATA, "the chunks of a wormhole transfer"), + ], + ) + session = spawn(setup, links, self._events) + self._session = session + self._tasks.append(asyncio.get_running_loop().create_task(self._dispatch(session))) + self._tasks.append(asyncio.get_running_loop().create_task(self._absorb(session))) + if not await session.ready(self._ready_timeout): + raise TransferError("the connection to the other computer did not come up") + self._say("Connected") + return session + + async def _absorb(self, session: OverlaySession) -> None: + """Routes that arrive later join the same session, so a second route is used as soon as it is up.""" + while True: + link = await self._inbound.get() + await session.add_link(link) + + async def _dispatch(self, session: OverlaySession) -> None: + """The session's events: streams the other side opens are authorised here, and a lost session is reported.""" + assert self._events is not None + while True: + event = await self._events.get() + if event.kind == "open_request": + if event.service in (CONTROL, DATA): + await session.authorize(event.stream, event.service, True) + await self._streams_q.put((event.stream, event.service)) + else: + await session.authorize(event.stream, event.service, False, "no such service") + elif event.kind == "down": + self._down.set() + return + elif event.kind == "route_changed": + state = "up" if event.up else "down" + self.routes_seen.append(f"{event.route.value} {state}") + + async def _next_inbound(self) -> Link: + try: + return await asyncio.wait_for(self._inbound.get(), self._accept_timeout) + except asyncio.TimeoutError as exc: + raise TimedOut("no connection from the other computer arrived in time") from exc + + # ----- the transit, as the session calls it ------------------------------------------------------ + + async def send(self, peer: P.PeerIdentity, offer: P.Offer, source: Path) -> None: + links = await self._dial(peer) + session = await self._start_session(peer, links) + self._say("Sending") + await self._send_data(session, offer, source) + + async def receive(self, peer: P.PeerIdentity, offer: P.Offer, folder: Path) -> Path: + self._say("Waiting for the connection") + first = await self._next_inbound() + session = await self._start_session(peer, [first]) + self._say("Receiving") + return await self._receive_data(session, offer, folder) + + def route_reports(self) -> list: + """The overlay's counters per route while the session is up: what each route carried and what it resent. Empty + before the session starts and after it has closed.""" + return self._session.routes() if self._session is not None else [] + + async def close(self) -> None: + for task in self._tasks: + task.cancel() + self._tasks = [] + if self._session is not None: + try: + await self._session.shutdown() + except Exception: + pass + self._session = None + for hub in [self._hub, *self._hubs.values()]: + if hub is not None: + try: + await hub.close() + except Exception: + pass + self._hub = None + self._hubs = {} + if self._server is not None: + self._server.close() + self._server = None + + # ----- sending ----------------------------------------------------------------------------------- + + async def _send_data(self, session: OverlaySession, offer: P.Offer, source: Path) -> None: + size = source.stat().st_size + if size != offer.size: + raise TransferError("the file changed after it was offered") + count = (size + CHUNK - 1) // CHUNK + header = { + "kind": offer.kind, + "name": offer.name, + "size": size, + "sha256": offer.sha256, + "streams": self._streams, + "chunk": CHUNK, + } + control = await session.open(CONTROL) + await session.send(control, P.encode(header) + b"\n") + reader = asyncio.get_running_loop().create_task(self._read_progress(session, control)) + self._tasks.append(reader) + try: + streams = [await session.open(DATA) for _ in range(self._streams)] + await asyncio.gather( + *(self._pump(session, stream, lane, size, count, source) for lane, stream in enumerate(streams)) + ) + finally: + reader.cancel() + + async def _pump(self, session: OverlaySession, stream: int, lane: int, size: int, count: int, source: Path) -> None: + """Send the chunks of one lane: chunk `lane`, `lane + streams`, and so on, then the end of the stream.""" + stride = self._streams + with open(source, "rb") as handle: + for index in range(lane, count, stride): + while self._sent - self._have_reported > WINDOW_BYTES: + self._progress.clear() + await self._wait(self._progress.wait()) + offset = index * CHUNK + length = min(CHUNK, size - offset) + handle.seek(offset) + data = handle.read(length) + if len(data) != length: + raise TransferError("the file changed while it was being sent") + await session.send(stream, FRAME.pack(offset, length) + data) + self._sent += length + await session.send(stream, b"", fin=True) + + async def _wait(self, awaitable) -> None: + """Wait for `awaitable`, but not for longer than the idle timeout, and not past a lost session.""" + waiter = asyncio.ensure_future(awaitable) + down = asyncio.ensure_future(self._down.wait()) + try: + done, _ = await asyncio.wait({waiter, down}, timeout=self._idle_timeout, return_when=asyncio.FIRST_COMPLETED) + if not done: + raise TransferError("the other computer stopped taking data") + if down in done and waiter not in done: + raise TransferError("the connection was lost") + finally: + waiter.cancel() + down.cancel() + + async def _read_progress(self, session: OverlaySession, control: int) -> None: + buffer = b"" + while True: + chunk = await session.recv(control) + if chunk is None: + return + buffer += chunk + if len(buffer) > _PROGRESS_LINE: + raise TransferError("the other computer sent too much progress") + while b"\n" in buffer: + line, _, buffer = buffer.partition(b"\n") + try: + have = int(json.loads(line.decode("utf-8"))["have"]) + except (ValueError, KeyError, TypeError): + continue + if have > self._have_reported: + self._have_reported = have + self._progress.set() + + # ----- receiving --------------------------------------------------------------------------------- + + async def _receive_data(self, session: OverlaySession, offer: P.Offer, folder: Path) -> Path: + folder.mkdir(parents=True, exist_ok=True) + part = folder / (offer.name + ".part") + state = _Receive(asyncio.Event(), asyncio.Event(), set(), activity=asyncio.get_running_loop().time()) + consumers: List[asyncio.Task] = [] + control_stream: List[int] = [] + loop = asyncio.get_running_loop() + + def maybe_done() -> None: + """Finished when every chunk has arrived and every data stream has ended. Waiting for the ends means the + sender's last frames are all in before the session is torn down, even for an empty file.""" + count = (state.size + CHUNK - 1) // CHUNK + if ( + state.header_ready.is_set() + and len(state.have) == count + and state.streams_expected > 0 + and state.streams_ended >= state.streams_expected + ): + state.done.set() + + async def control_reader(stream: int) -> None: + control_stream.append(stream) + buffer = b"" + while not state.header_ready.is_set(): + chunk = await session.recv(stream) + if chunk is None: + raise TransferError("the header never arrived") + buffer += chunk + if b"\n" in buffer: + line, _, _rest = buffer.partition(b"\n") + header = self._check_header(line, offer) + state.size = header["size"] + state.streams_expected = header["streams"] + state.file = open(part, "w+b") + state.file.truncate(state.size) + state.header_ready.set() + maybe_done() + # Nothing more is expected from the sender on the control stream; keep reading until it ends. + while True: + if await session.recv(stream) is None: + return + + async def data_reader(stream: int) -> None: + buffer = bytearray() + while True: + chunk = await session.recv(stream) + if chunk is None: + break + buffer += chunk + await state.header_ready.wait() + state.activity = loop.time() + while len(buffer) >= FRAME.size: + offset, length = FRAME.unpack_from(buffer, 0) + if offset % CHUNK or offset >= state.size or length != min(CHUNK, state.size - offset): + raise TransferError("a chunk is out of range for this file") + if len(buffer) < FRAME.size + length: + break + payload = bytes(buffer[FRAME.size : FRAME.size + length]) + del buffer[: FRAME.size + length] + index = offset // CHUNK + if index in state.have: + continue + state.file.seek(offset) + state.file.write(payload) + state.have.add(index) + state.have_bytes += length + if state.have_bytes - state.reported >= PROGRESS_BYTES: + await self._report(session, control_stream, state) + maybe_done() + if buffer: + raise TransferError("a data stream ended in the middle of a chunk") + state.streams_ended += 1 + maybe_done() + + async def consume() -> None: + while True: + stream, service = await self._streams_q.get() + if service == CONTROL: + consumers.append(loop.create_task(control_reader(stream))) + else: + consumers.append(loop.create_task(data_reader(stream))) + + consumer = loop.create_task(consume()) + try: + waiting = asyncio.ensure_future(state.done.wait()) + down = asyncio.ensure_future(self._down.wait()) + while True: + failed = [t for t in consumers if t.done() and not t.cancelled() and t.exception() is not None] + if failed: + raise failed[0].exception() # type: ignore[misc] + done, _ = await asyncio.wait({waiting, down}, timeout=1.0, return_when=asyncio.FIRST_COMPLETED) + if waiting in done or state.done.is_set(): + break + if down in done: + raise TransferError("the connection was lost") + if loop.time() - state.activity > self._idle_timeout: + raise TransferError("the other computer stopped sending") + waiting.cancel() + down.cancel() + if len(state.have) != (state.size + CHUNK - 1) // CHUNK: + raise TransferError("some of the data did not arrive") + await self._report(session, control_stream, state, final=True) + if state.file is not None: + state.file.flush() + state.file.close() + return part + except BaseException: + if state.file is not None: + state.file.close() + try: + part.unlink() + except OSError: + pass + raise + finally: + consumer.cancel() + for task in consumers: + task.cancel() + + async def _report(self, session: OverlaySession, control_stream: List[int], state: _Receive, final: bool = False) -> None: + if not control_stream: + return + state.reported = state.have_bytes + line = json.dumps({"have": state.have_bytes if not final else state.size}).encode("utf-8") + b"\n" + try: + await session.send(control_stream[0], line) + except Exception: + if final: + raise + + @staticmethod + def _check_header(line: bytes, offer: P.Offer) -> dict: + try: + header = json.loads(line.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise TransferError("the header is not JSON") from exc + if not isinstance(header, dict): + raise TransferError("the header is not an object") + if header.get("kind") != offer.kind or header.get("name") != offer.name: + raise TransferError("the header does not match the offer") + if header.get("size") != offer.size or header.get("sha256") != offer.sha256: + raise TransferError("the header does not match the offer") + if header.get("chunk") != CHUNK: + raise TransferError("the chunk size is not one this app speaks") + streams = header.get("streams") + if not isinstance(streams, int) or not 1 <= streams <= STREAMS_MAX: + raise TransferError("the stream count is out of range") + return header + + +__all__ = ["CONTROL", "DATA", "OverlayTransit", "STREAMS_DEFAULT", "WINDOW_BYTES"] diff --git a/gui/transferd_gui/wormhole/errors.py b/gui/transferd_gui/wormhole/errors.py new file mode 100644 index 0000000..568be82 --- /dev/null +++ b/gui/transferd_gui/wormhole/errors.py @@ -0,0 +1,43 @@ +"""The errors a wormhole raises. Each one carries a message fit to show the user.""" + +from __future__ import annotations + + +class WormholeError(Exception): + """Anything that stops a wormhole. The message is what the user is told.""" + + +class CodeError(WormholeError, ValueError): + """The code does not read back: a missing or misplaced word, an unknown word, or a bad nameplate.""" + + +class PakeError(WormholeError): + """The key exchange failed: a malformed message from the other side.""" + + +class OpenError(WormholeError): + """A sealed message did not open. The code is wrong, or the message was changed, or it is not for this exchange.""" + + +class MailboxError(WormholeError): + """The mailbox refused a request, or could not be reached, or closed the connection. + + `code` is the mailbox's own code for a refusal (for example "rate_limited" or "busy"), or "" when there is none, and + `retry_after` is how many seconds the mailbox asked the caller to wait before trying again, or 0.""" + + def __init__(self, message: str = "", *, code: str = "", retry_after: float = 0.0) -> None: + super().__init__(message) + self.code = code + self.retry_after = retry_after + + +class ProtocolError(WormholeError): + """The other side sent something the protocol does not allow at this point.""" + + +class TimedOut(WormholeError): + """The other side did not do its part in time. Usually it was never there, or it closed the app.""" + + +class TransferError(WormholeError): + """A file or folder did not arrive whole: a hash that does not match, a size that is wrong, or an unsafe name.""" diff --git a/gui/transferd_gui/wormhole/keys.py b/gui/transferd_gui/wormhole/keys.py new file mode 100644 index 0000000..bbe2ae7 --- /dev/null +++ b/gui/transferd_gui/wormhole/keys.py @@ -0,0 +1,113 @@ +"""The keys of a wormhole: the SPAKE2 exchange, the phase keys, and the seal that protects every message after the first. + +Everything here is pure: no network, no clock. The session runs these in order. + + pake = Pake(code.password()) # send pake.outbound() in phase "pake" + keys = pake.finish(peer_pake_message) # the root key; the same on both sides when the code is the same + sealed = seal(keys, my_side, "version", message_id, plaintext) + plaintext = open_sealed(keys, peer_side, "version", peer_message_id, sealed) +""" + +from __future__ import annotations + +import os + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from spake2 import SPAKE2_Symmetric + +from transferd.crypto import blake3_derive_key +from transferd_gui.wormhole.errors import OpenError, PakeError + +#: The identity both sides give SPAKE2. It names the protocol, so a code for another protocol cannot be used here. +APP_ID = b"transferd-wormhole/1" +ROOT_CONTEXT = "transferd-wormhole/1 root" +PHASE_CONTEXT = "transferd-wormhole/1 phase " +AAD_PREFIX = b"transferd-wormhole/1" +NONCE_BYTES = 12 +TAG_BYTES = 16 +SIDE_HEX = 16 +MESSAGE_ID_HEX = 4 + + +def new_side() -> str: + """A side id: 16 random hex characters, one per attempt. It is not secret, and it is never reused.""" + return os.urandom(SIDE_HEX // 2).hex() + + +def new_message_id() -> str: + """A message id: 4 random hex characters, unique per message within a mailbox.""" + return os.urandom(MESSAGE_ID_HEX // 2).hex() + + +def check_side(side: str) -> str: + if not isinstance(side, str) or len(side) != SIDE_HEX or any(c not in "0123456789abcdef" for c in side): + raise PakeError("a side id is 16 lower-case hex characters") + return side + + +class Pake: + """One side's half of SPAKE2. Make it, send `outbound`, then `finish` with the other side's message. + + A Pake is used once. The library allows one `finish` call and a bad message uses it up, so a second call is refused + here, with a message, rather than failing inside the library. + """ + + def __init__(self, password: bytes) -> None: + self._spake = SPAKE2_Symmetric(password, idSymmetric=APP_ID) + self._outbound = self._spake.start() + self._finished = False + + @property + def outbound(self) -> bytes: + return self._outbound + + def finish(self, peer_message: bytes) -> "Keys": + """The root key. A malformed message raises `PakeError`; a wrong code does not show here, but in the next phase.""" + if self._finished: + raise PakeError("the key exchange is already finished; start a new one") + self._finished = True + if not isinstance(peer_message, (bytes, bytearray)) or not peer_message: + raise PakeError("the other side's key exchange message is empty") + try: + shared = self._spake.finish(bytes(peer_message)) + except (AssertionError, ValueError) as exc: + raise PakeError("the other side's key exchange message is not valid") from exc + return Keys(blake3_derive_key(ROOT_CONTEXT, shared)) + + +class Keys: + """The root key of one wormhole. Each side derives a separate key for each phase it sends in.""" + + def __init__(self, root: bytes) -> None: + if len(root) != 32: + raise PakeError("the root key is 32 bytes") + self._root = bytes(root) + + def phase_key(self, side: str, phase: str) -> bytes: + """The key `side` uses to send in `phase`. Both sides can derive it; a side never accepts its own messages.""" + check_side(side) + return blake3_derive_key(PHASE_CONTEXT + phase, self._root + side.encode("ascii")) + + +def _aad(side: str, phase: str, message_id: str) -> bytes: + return b"\x00".join([AAD_PREFIX, side.encode("ascii"), phase.encode("ascii"), message_id.encode("ascii")]) + + +def seal(keys: Keys, side: str, phase: str, message_id: str, plaintext: bytes) -> bytes: + """Encrypt a message from `side` in `phase`. The result is nonce || ciphertext || tag.""" + nonce = os.urandom(NONCE_BYTES) + key = keys.phase_key(side, phase) + return nonce + AESGCM(key).encrypt(nonce, bytes(plaintext), _aad(side, phase, message_id)) + + +def open_sealed(keys: Keys, side: str, phase: str, message_id: str, sealed: bytes) -> bytes: + """Decrypt a message `side` sent in `phase`. Raises `OpenError` if it was changed, belongs elsewhere, or the code is wrong.""" + if len(sealed) < NONCE_BYTES + TAG_BYTES: + raise OpenError("a message is too short to be real") + nonce, body = sealed[:NONCE_BYTES], sealed[NONCE_BYTES:] + key = keys.phase_key(side, phase) + try: + return AESGCM(key).decrypt(nonce, body, _aad(side, phase, message_id)) + except InvalidTag as exc: + raise OpenError("the code is wrong, or the message was changed") from exc diff --git a/gui/transferd_gui/wormhole/mailbox.py b/gui/transferd_gui/wormhole/mailbox.py new file mode 100644 index 0000000..f7f2af2 --- /dev/null +++ b/gui/transferd_gui/wormhole/mailbox.py @@ -0,0 +1,471 @@ +"""The mailbox client: one side's connection to a wormhole mailbox, with what a real network needs. + +- Addresses. `MailboxClient` takes the list from Settings (see `addresses.py`) and tries it in order, for a few rounds, with a + growing and randomised pause between rounds. Plain ws:// is only ever used for this computer. +- Pins. An address with a pin must present the pinned certificate. That is checked after the handshake and before anything + is sent, so a different server never sees this side's nameplate. +- One mailbox. Two sides can only meet on the same server. So once connected, this client stays on that mailbox: a + reconnect goes back to it, and a fallback to another one happens only before a meeting has begun. +- Refusals for rate. A request refused with `rate_limited` is sent again after the time the mailbox asked for, and so is a + message refused that way, rather than failing its caller. + +A message that was sent but not confirmed is kept and sent again after `reconnect`. A message that arrived is delivered +once, however many times the mailbox replays it. An acknowledgement that could not be sent is sent after the next connect. +The server side of the protocol is `transferd_gui.wormhole.server`. +""" + +from __future__ import annotations + +import asyncio +import json +import random +import ssl +from dataclasses import dataclass +from typing import Dict, Optional, Sequence, Set, Tuple, Union + +from websockets.asyncio.client import ClientConnection, connect +from websockets.exceptions import ConnectionClosed, WebSocketException + +from transferd_gui.wormhole import keys, tls +from transferd_gui.wormhole.addresses import MailboxAddress, parse_list +from transferd_gui.wormhole.errors import MailboxError +from transferd_gui.wormhole.server import APP_ID, MAX_MESSAGE_BYTES, MOODS, PROTOCOL + +CONNECT_ATTEMPTS = 3 +BACKOFF_S = 0.5 +BACKOFF_CAP_S = 8.0 +#: A request refused for its rate is sent again this many times at most, and only when the wait asked for is this short. +RATE_RETRIES = 4 +RATE_WAIT_MAX_S = 10.0 +RATE_CODE = "rate_limited" + + +class _PinMismatch(MailboxError): + """The mailbox presented a certificate other than the pinned one. Trying that address again cannot help.""" + + +@dataclass(frozen=True) +class Incoming: + """A message from the other side, as the mailbox gave it. The caller acks it once it has been dealt with.""" + + side: str + phase: str + message_id: str + body: bytes + + +class MailboxClient: + """One side's connection. Call `connect`, then `allocate` or `claim`, then `open`, then `add` and `receive`. + + `mailboxes` is the Settings list as text, or a sequence of addresses. A single `ws://` or `wss://` address is a list of one. + """ + + def __init__( + self, + mailboxes: Union[str, Sequence[MailboxAddress]], + side: str, + *, + timeout: float = 15.0, + attempts: int = CONNECT_ATTEMPTS, + backoff: float = BACKOFF_S, + backoff_cap: float = BACKOFF_CAP_S, + ) -> None: + if isinstance(mailboxes, str): + try: + addresses = parse_list(mailboxes) + except ValueError as exc: + raise MailboxError(f"the mailbox setting: {exc}") from exc + else: + addresses = tuple(mailboxes) + if not addresses: + raise MailboxError("no mailbox is set; add one in Settings (Wormhole)") + self.addresses: Tuple[MailboxAddress, ...] = addresses + self.url: Optional[str] = None + self.side = keys.check_side(side) + self.timeout = timeout + self.attempts = max(1, int(attempts)) + self.backoff = backoff + self.backoff_cap = backoff_cap + self.nameplate: Optional[int] = None + self.mailbox_id: Optional[str] = None + self.limits: dict = {"max_message_bytes": MAX_MESSAGE_BYTES} + self.connected = False + self._current: Optional[MailboxAddress] = None + self._ws: Optional[ClientConnection] = None + self._reader: Optional[asyncio.Task] = None + self._background: Set[asyncio.Task] = set() + self._lock = asyncio.Lock() + self._welcome: Optional[asyncio.Future] = None + self._waiter: Optional[Tuple[str, Set[str], asyncio.Future]] = None + self._inbox: asyncio.Queue = asyncio.Queue() + self._seen: Set[Tuple[str, str]] = set() + self._added: Dict[str, asyncio.Future] = {} + self._unconfirmed: Dict[str, dict] = {} + self._pending_acks: Set[str] = set() + self._opened = False + + # ----- connection -------------------------------------------------------------------------------- + + async def connect(self) -> None: + """Connect and check the mailbox's greeting. Tries the addresses in order, for `attempts` rounds. Once a mailbox has + been used, every later connection goes to that same mailbox only.""" + candidates = (self._current,) if self._current is not None else self.addresses + refused: Set[MailboxAddress] = set() + last: Optional[MailboxError] = None + for attempt in range(self.attempts): + for address in candidates: + if address in refused: + continue + try: + await self._open(address) + return + except _PinMismatch as exc: + refused.add(address) + last = exc + except MailboxError as exc: + last = exc + if len(refused) == len(candidates) or attempt + 1 == self.attempts: + break + hint = last.retry_after if last is not None and last.code in ("busy", RATE_CODE) else 0.0 + await asyncio.sleep(self._pause(attempt, hint)) + raise last if last is not None else MailboxError("no mailbox answered") + + async def _open(self, address: MailboxAddress) -> None: + if address.scheme == "ws" and not address.loopback: + raise MailboxError(f"ws:// reaches only this computer; {address.url} is refused") + try: + ws = await connect( + address.url, + ssl=_context_for(address), + max_size=2 * MAX_MESSAGE_BYTES + 8192, + open_timeout=self.timeout, + ping_interval=20, + ping_timeout=20, + close_timeout=5, + proxy=None if address.loopback else True, + ) + except ssl.SSLError as exc: + raise MailboxError(f"the mailbox at {address.url} did not present a certificate this computer accepts") from exc + except (OSError, WebSocketException, TimeoutError) as exc: + raise MailboxError(f"could not reach the mailbox at {address.url}") from exc + if address.pin: + seen = tls.peer_fingerprint(ws) + if seen != address.pin: + await _close_quietly(ws) + raise _PinMismatch( + f"the mailbox at {address.url} is not the one pinned in Settings: it presented a different certificate" + ) + self._ws = ws + self.connected = True + loop = asyncio.get_running_loop() + self._welcome = loop.create_future() + self._reader = loop.create_task(self._read_loop(ws)) + try: + welcome = await asyncio.wait_for(self._welcome, self.timeout) + except asyncio.TimeoutError as exc: + await self.disconnect() + raise MailboxError(f"the mailbox at {address.url} did not greet this computer in time") from exc + except MailboxError: + await self.disconnect() + raise + if welcome.get("protocol", PROTOCOL) != PROTOCOL: + await self.disconnect() + raise MailboxError( + f"the mailbox at {address.url} speaks protocol {welcome.get('protocol')}; this computer speaks {PROTOCOL}" + ) + limits = welcome.get("limits") + if isinstance(limits, dict): + self.limits.update(limits) + self.url = address.url + self._current = address + await self._send({"type": "bind", "appid": APP_ID, "side": self.side}) + + def _pause(self, attempt: int, hint: float = 0.0) -> float: + """How long to wait before the next round: exponential, capped, randomised, and never less than the mailbox asked.""" + growth = min(self.backoff_cap, self.backoff * (2 ** attempt)) + return max(min(hint, RATE_WAIT_MAX_S), growth * (0.5 + random.random() / 2)) + + async def disconnect(self) -> None: + self.connected = False + for task in list(self._background): + task.cancel() + if self._reader is not None: + self._reader.cancel() + try: + await self._reader + except (asyncio.CancelledError, Exception): + pass + self._reader = None + if self._ws is not None: + try: + await self._ws.close() + except Exception: + pass + self._ws = None + + async def reconnect(self) -> None: + """Connect again to the same mailbox, rejoin it, and send what the last connection did not confirm.""" + await self.disconnect() + await self.connect() + if self.mailbox_id is not None and self._opened: + await self._request({"type": "open", "mailbox": self.mailbox_id}, ("opened",)) + for payload in list(self._unconfirmed.values()): + await self._send(payload) + for message_id in list(self._pending_acks): + await self._send(self._ack_payload(message_id)) + self._pending_acks.clear() + + # ----- the mailbox ------------------------------------------------------------------------------- + + async def allocate(self) -> int: + reply = await self._request({"type": "allocate"}, ("allocated",)) + self.nameplate = int(reply["nameplate"]) + return self.nameplate + + async def claim(self, nameplate: int) -> str: + reply = await self._request({"type": "claim", "nameplate": str(nameplate)}, ("claimed",)) + self.nameplate = nameplate + self.mailbox_id = str(reply["mailbox"]) + return self.mailbox_id + + async def open(self) -> None: + """Join the mailbox. The messages the other side sent before this are delivered first, then new ones.""" + if self.mailbox_id is None: + raise MailboxError("claim a nameplate before opening its mailbox") + await self._request({"type": "open", "mailbox": self.mailbox_id}, ("opened",)) + self._opened = True + + async def add(self, phase: str, body: bytes, message_id: Optional[str] = None) -> str: + """Send one message. Returns once the mailbox has stored it. Raises `MailboxError` if it is not confirmed in time; + it is still kept, and `reconnect` followed by `flush` sends it again. + + The caller may choose the id, because the id is part of what the body is sealed to. Otherwise one is made.""" + if self.mailbox_id is None: + raise MailboxError("claim a nameplate before sending") + limit = int(self.limits.get("max_message_bytes", MAX_MESSAGE_BYTES)) + if len(body) > limit: + raise MailboxError(f"a message is at most {limit} bytes; this one is {len(body)}") + if message_id is None: + message_id = keys.new_message_id() + while message_id in self._unconfirmed or message_id in self._added: + message_id = keys.new_message_id() + elif message_id in self._unconfirmed or message_id in self._added: + raise MailboxError("this message id is already in use") + payload = { + "type": "add", + "mailbox": self.mailbox_id, + "id": message_id, + "phase": phase, + "body": body.hex(), + } + future = asyncio.get_running_loop().create_future() + self._added[message_id] = future + self._unconfirmed[message_id] = payload + if self.connected: + await self._send(payload) + try: + # Shielded: a timeout here must not cancel the future, because `flush` and a later reply still use it. + await asyncio.wait_for(asyncio.shield(future), self.timeout) + except asyncio.TimeoutError as exc: + raise MailboxError("the mailbox did not confirm a message in time") from exc + return message_id + + async def flush(self) -> None: + """Wait until every message this client sent has been confirmed. Sends again the ones that were not.""" + if self.connected: + for payload in list(self._unconfirmed.values()): + await self._send(payload) + futures = [future for mid, future in self._added.items() if mid in self._unconfirmed] + if not futures: + return + done, pending = await asyncio.wait(futures, timeout=self.timeout) + if pending: + raise MailboxError("some messages are still not confirmed by the mailbox") + for future in done: + if future.exception() is not None: + raise future.exception() + + async def receive(self, timeout: float) -> Optional[Incoming]: + """The next message from the other side, or None if none came in `timeout` seconds.""" + try: + return await asyncio.wait_for(self._inbox.get(), timeout) + except asyncio.TimeoutError: + return None + + async def ack(self, message_id: str) -> None: + """Tell the mailbox a message has been dealt with, so it is not sent again. Kept and sent after a reconnect if the + connection is down now.""" + if self.connected and self.mailbox_id is not None: + try: + await self._send(self._ack_payload(message_id)) + return + except MailboxError: + pass + self._pending_acks.add(message_id) + + async def close(self, mood: str = "happy") -> None: + """Close the mailbox for this side, and disconnect. The mailbox is removed once both sides have closed.""" + if mood not in MOODS: + raise MailboxError(f"a mood is one of {', '.join(MOODS)}") + if self.connected and self.mailbox_id is not None: + try: + await self._request({"type": "close", "mailbox": self.mailbox_id, "mood": mood}, ("closed",)) + except MailboxError: + pass + await self.disconnect() + + async def release(self) -> None: + if self.connected and self.nameplate is not None: + await self._request({"type": "release", "nameplate": str(self.nameplate)}, ("released",)) + + # ----- plumbing ---------------------------------------------------------------------------------- + + def _ack_payload(self, message_id: str) -> dict: + return {"type": "ack", "mailbox": self.mailbox_id, "id": message_id} + + async def _send(self, payload: dict) -> None: + if self._ws is None or not self.connected: + raise MailboxError("not connected to the mailbox") + try: + await self._ws.send(json.dumps(payload, separators=(",", ":"))) + except ConnectionClosed as exc: + self.connected = False + raise MailboxError("the mailbox connection closed") from exc + + async def _request(self, payload: dict, expect: Sequence[str]) -> dict: + async with self._lock: + for attempt in range(RATE_RETRIES + 1): + future = asyncio.get_running_loop().create_future() + self._waiter = (payload["type"], set(expect), future) + try: + await self._send(payload) + return await asyncio.wait_for(future, self.timeout) + except asyncio.TimeoutError as exc: + raise MailboxError(f"the mailbox did not answer '{payload['type']}' in time") from exc + except MailboxError as exc: + if exc.code != RATE_CODE or attempt == RATE_RETRIES or exc.retry_after > RATE_WAIT_MAX_S: + raise + await asyncio.sleep(exc.retry_after) + finally: + self._waiter = None + raise MailboxError(f"the mailbox kept refusing '{payload['type']}'") + + def _resend_later(self, message_id: str, delay: float) -> None: + task = asyncio.get_running_loop().create_task(self._resend(message_id, delay)) + self._background.add(task) + task.add_done_callback(self._background.discard) + + async def _resend(self, message_id: str, delay: float) -> None: + await asyncio.sleep(delay) + payload = self._unconfirmed.get(message_id) + if payload is not None and self.connected: + try: + await self._send(payload) + except MailboxError: + pass + + async def _read_loop(self, ws: ClientConnection) -> None: + try: + async for raw in ws: + try: + message = json.loads(raw) + except (TypeError, ValueError): + continue + if isinstance(message, dict): + self._on_message(message) + except (ConnectionClosed, WebSocketException, OSError): + pass + finally: + if self._ws is ws: + self.connected = False + self._fail_waiter("the mailbox connection closed") + + def _on_message(self, message: dict) -> None: + kind = message.get("type") + if kind == "message": + self._on_incoming(message) + elif kind == "added": + message_id = message.get("id") + self._unconfirmed.pop(message_id, None) + future = self._added.pop(message_id, None) + if future is not None and not future.done(): + future.set_result(None) + elif kind == "welcome": + if self._welcome is not None and not self._welcome.done(): + self._welcome.set_result(message) + elif kind == "error": + self._on_error(message) + elif self._waiter is not None: + request, expect, future = self._waiter + if kind in expect and not future.done(): + future.set_result(message) + + def _on_incoming(self, message: dict) -> None: + side = message.get("side") + message_id = message.get("id") + phase = message.get("phase") + body = message.get("body") + if not (isinstance(side, str) and isinstance(message_id, str) and isinstance(phase, str) and isinstance(body, str)): + return + if (side, message_id) in self._seen: + return + try: + raw = bytes.fromhex(body) + except ValueError: + return + self._seen.add((side, message_id)) + self._inbox.put_nowait(Incoming(side, phase, message_id, raw)) + + def _on_error(self, message: dict) -> None: + text = str(message.get("error", "the mailbox refused a request")) + code = str(message.get("code", "")) + retry = _seconds(message.get("retry_after")) + orig = message.get("orig") + if self._welcome is not None and not self._welcome.done(): + # Before the greeting, the mailbox is refusing the connection itself (for example, that it is busy). + self._welcome.set_exception(MailboxError(text, code=code, retry_after=retry)) + return + if orig == "add": + message_id = message.get("id") + if code == RATE_CODE and message_id in self._unconfirmed: + # The mailbox will take this message after the wait it asked for, so it is sent again rather than failed. + self._resend_later(message_id, retry) + return + # Any other refusal: the mailbox will not take the message, so it is not sent again, and its caller is told. + self._unconfirmed.pop(message_id, None) + future = self._added.pop(message_id, None) + if future is not None and not future.done(): + future.set_exception(MailboxError(text, code=code, retry_after=retry)) + return + if self._waiter is not None and (orig is None or orig == self._waiter[0]): + _request, _expect, future = self._waiter + if not future.done(): + future.set_exception(MailboxError(text, code=code, retry_after=retry)) + + def _fail_waiter(self, text: str) -> None: + if self._welcome is not None and not self._welcome.done(): + self._welcome.set_exception(MailboxError(text)) + if self._waiter is not None: + _request, _expect, future = self._waiter + if not future.done(): + future.set_exception(MailboxError(text)) + + +def _context_for(address: MailboxAddress) -> Optional[ssl.SSLContext]: + if address.scheme == "ws": + return None + return tls.pinned_context() if address.pin else tls.system_context() + + +def _seconds(value) -> float: + try: + return max(0.0, float(value)) + except (TypeError, ValueError): + return 0.0 + + +async def _close_quietly(ws: ClientConnection) -> None: + try: + await ws.close() + except Exception: + pass diff --git a/gui/transferd_gui/wormhole/protocol.py b/gui/transferd_gui/wormhole/protocol.py new file mode 100644 index 0000000..34dc1e4 --- /dev/null +++ b/gui/transferd_gui/wormhole/protocol.py @@ -0,0 +1,301 @@ +"""The wormhole's messages: what each sealed phase carries, how it is checked, and how it is written. + +Every message after `pake` is a JSON object. A message that does not have the expected fields, types and sizes is refused +with `ProtocolError`, before anything it says is used. The checks are strict on purpose: the other side is a stranger until +the phases have been opened, and even then its values reach the file system, the screen and the overlay. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import dataclass, field +from typing import Any, Dict + +from transferd.frames import VERSION_CURRENT as OVERLAY_VERSION +from transferd.identity import HYBRID_PK_LEN +from transferd_gui.backend.files import NAME_MAX +from transferd_gui.wormhole.errors import ProtocolError + +PROTOCOL_VERSION = 1 +APP = "transferd-wormhole/1" +FEATURES = ("parallel-streams", "sha256") +TEXT_MAX_BYTES = 16 * 1024 +SIZE_MAX = 1 << 40 +ENTRIES_MAX = 10_000 +HINTS_MAX = 8 +NAME_TEXT_MAX = 64 +RELAY_MAX = 128 +REASON_MAX = 200 +JSON_MAX = 64 * 1024 +KINDS = ("text", "file", "directory") +NODE_ID_HEX = 64 +SHA256_HEX = 64 +_HEX = re.compile(r"[0-9a-f]*") +_UNSAFE_NAME = re.compile(r"[\x00-\x1f\\/]") + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +# ----- reading fields --------------------------------------------------------------------------------- + + +def _field(obj: Dict[str, Any], key: str, kind: type, where: str): + if key not in obj: + raise ProtocolError(f"{where}: '{key}' is missing") + value = obj[key] + if kind is int and isinstance(value, bool): + raise ProtocolError(f"{where}: '{key}' is a number") + if not isinstance(value, kind): + raise ProtocolError(f"{where}: '{key}' is not a {kind.__name__}") + return value + + +def _text(obj: Dict[str, Any], key: str, where: str, *, maximum: int, allow_empty: bool = False) -> str: + value = _field(obj, key, str, where) + if not allow_empty and not value: + raise ProtocolError(f"{where}: '{key}' is empty") + if len(value.encode("utf-8", errors="strict")) > maximum: + raise ProtocolError(f"{where}: '{key}' is longer than {maximum}") + return value + + +def _number(obj: Dict[str, Any], key: str, where: str, *, maximum: int) -> int: + value = _field(obj, key, int, where) + if not 0 <= value <= maximum: + raise ProtocolError(f"{where}: '{key}' is outside 0 to {maximum}") + return value + + +def _hex(obj: Dict[str, Any], key: str, where: str, *, length: int) -> str: + value = _text(obj, key, where, maximum=length) + if len(value) != length or not _HEX.fullmatch(value): + raise ProtocolError(f"{where}: '{key}' is {length} lower-case hex characters") + return value + + +def safe_offered_name(name: str) -> str: + """A name from the other side, reduced to something that can be a file name on any computer.""" + if not isinstance(name, str) or _UNSAFE_NAME.search(name): + raise ProtocolError("a name has a path separator or a control character") + base = name.strip(" .") + if not base: + raise ProtocolError("a name is empty") + if len(base.encode("utf-8")) > NAME_MAX: + raise ProtocolError(f"a name is longer than {NAME_MAX} bytes") + return base + + +# ----- messages --------------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Version: + protocol: int + app: str + overlay: int + features: tuple + + @classmethod + def ours(cls) -> "Version": + return cls(PROTOCOL_VERSION, APP, OVERLAY_VERSION, FEATURES) + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> "Version": + where = "version" + protocol = _number(obj, "protocol", where, maximum=255) + app = _text(obj, "app", where, maximum=64) + overlay = _number(obj, "overlay", where, maximum=255) + raw = _field(obj, "features", list, where) + if len(raw) > 16 or not all(isinstance(f, str) and len(f) <= 32 for f in raw): + raise ProtocolError("version: 'features' is a short list of names") + return cls(protocol, app, overlay, tuple(raw)) + + def to_dict(self) -> Dict[str, Any]: + return {"protocol": self.protocol, "app": self.app, "overlay": self.overlay, "features": list(self.features)} + + def check(self) -> None: + """Refuse a version we cannot speak. Both sides must agree on the protocol and on the overlay.""" + if self.app != APP: + raise ProtocolError(f"the other side speaks '{self.app}', not {APP}") + if self.protocol != PROTOCOL_VERSION: + raise ProtocolError(f"the other side speaks protocol {self.protocol}; this app speaks {PROTOCOL_VERSION}") + if self.overlay != OVERLAY_VERSION: + raise ProtocolError(f"the other side's overlay is version {self.overlay}; this app's is {OVERLAY_VERSION}") + + +@dataclass(frozen=True) +class Hint: + host: str + port: int + + @classmethod + def from_dict(cls, obj: Any) -> "Hint": + if not isinstance(obj, dict): + raise ProtocolError("identity: a hint is an object") + if obj.get("kind") != "direct": + raise ProtocolError("identity: an unknown hint kind") + host = _text(obj, "host", "identity hint", maximum=255) + port = _number(obj, "port", "identity hint", maximum=65535) + if port == 0: + raise ProtocolError("identity: a hint's port is 1 to 65535") + return cls(host, port) + + def to_dict(self) -> Dict[str, Any]: + return {"kind": "direct", "host": self.host, "port": self.port} + + +@dataclass(frozen=True) +class PeerIdentity: + """The other side's ephemeral identity for one attempt, and where it can be reached.""" + + node_id: str + public_key: bytes + name: str + relay: str + hints: tuple = field(default_factory=tuple) + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> "PeerIdentity": + where = "identity" + node_id = _hex(obj, "node_id", where, length=NODE_ID_HEX) + public_hex = _hex(obj, "public_key", where, length=HYBRID_PK_LEN * 2) + name = _text(obj, "name", where, maximum=NAME_TEXT_MAX, allow_empty=True) + relay = _text(obj, "relay", where, maximum=RELAY_MAX, allow_empty=True) + raw_hints = _field(obj, "hints", list, where) + if len(raw_hints) > HINTS_MAX: + raise ProtocolError(f"identity: at most {HINTS_MAX} hints") + hints = tuple(Hint.from_dict(h) for h in raw_hints) + return cls(node_id, bytes.fromhex(public_hex), name, relay, hints) + + def to_dict(self) -> Dict[str, Any]: + return { + "node_id": self.node_id, + "public_key": self.public_key.hex(), + "name": self.name, + "relay": self.relay, + "hints": [h.to_dict() for h in self.hints], + } + + +@dataclass(frozen=True) +class Offer: + """What the sender is sending. A file's bytes travel over the overlay; a text is inside this message.""" + + kind: str + name: str = "" + size: int = 0 + sha256: str = "" + text: str = "" + entries: int = 0 + + @classmethod + def for_text(cls, text: str) -> "Offer": + data = text.encode("utf-8") + if len(data) > TEXT_MAX_BYTES: + raise ProtocolError(f"a text is at most {TEXT_MAX_BYTES} bytes") + return cls("text", "", len(data), sha256_hex(data), text, 0) + + @classmethod + def for_file(cls, name: str, size: int, sha256: str) -> "Offer": + return cls("file", safe_offered_name(name), size, sha256, "", 0) + + @classmethod + def for_directory(cls, name: str, size: int, sha256: str, entries: int) -> "Offer": + return cls("directory", safe_offered_name(name), size, sha256, "", entries) + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> "Offer": + where = "offer" + kind = _field(obj, "kind", str, where) + if kind not in KINDS: + raise ProtocolError(f"offer: the kind is not one of {', '.join(KINDS)}") + if kind == "text": + text = _text(obj, "text", where, maximum=TEXT_MAX_BYTES, allow_empty=True) + size = len(text.encode("utf-8")) + return cls("text", "", size, sha256_hex(text.encode("utf-8")), text, 0) + name = safe_offered_name(_field(obj, "name", str, where)) + size = _number(obj, "size", where, maximum=SIZE_MAX) + sha = _hex(obj, "sha256", where, length=SHA256_HEX) + entries = _number(obj, "entries", where, maximum=ENTRIES_MAX) if kind == "directory" else 0 + return cls(kind, name, size, sha, "", entries) + + def to_dict(self) -> Dict[str, Any]: + if self.kind == "text": + return {"kind": "text", "text": self.text} + out: Dict[str, Any] = {"kind": self.kind, "name": self.name, "size": self.size, "sha256": self.sha256} + if self.kind == "directory": + out["entries"] = self.entries + return out + + +@dataclass(frozen=True) +class Answer: + accept: bool + reason: str = "" + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> "Answer": + accept = _field(obj, "accept", bool, "answer") + reason = _text(obj, "reason", "answer", maximum=REASON_MAX, allow_empty=True) if "reason" in obj else "" + return cls(accept, reason) + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"accept": self.accept} + if self.reason: + out["reason"] = self.reason[:REASON_MAX] + return out + + +@dataclass(frozen=True) +class Done: + ok: bool + sha256: str = "" + reason: str = "" + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> "Done": + ok = _field(obj, "ok", bool, "done") + sha = _hex(obj, "sha256", "done", length=SHA256_HEX) if obj.get("sha256") else "" + reason = _text(obj, "reason", "done", maximum=REASON_MAX, allow_empty=True) if "reason" in obj else "" + return cls(ok, sha, reason) + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"ok": self.ok} + if self.sha256: + out["sha256"] = self.sha256 + if self.reason: + out["reason"] = self.reason[:REASON_MAX] + return out + + +# ----- bytes ------------------------------------------------------------------------------------------ + + +def encode(message: Any) -> bytes: + """A message as bytes. Sorted keys and no spaces, so the same message is always the same bytes.""" + raw = json.dumps(message, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + if len(raw) > JSON_MAX: + raise ProtocolError(f"a message is at most {JSON_MAX} bytes") + return raw + + +def decode(raw: bytes) -> Dict[str, Any]: + """Bytes to a JSON object. Anything else is refused.""" + if len(raw) > JSON_MAX: + raise ProtocolError(f"a message is at most {JSON_MAX} bytes") + try: + obj = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise ProtocolError("a message is not JSON text") from exc + if not isinstance(obj, dict): + raise ProtocolError("a message is a JSON object") + return obj + + +def parse(raw: bytes, what) -> Any: + """Decode bytes and build the message type `what` from them, checking every field.""" + return what.from_dict(decode(raw)) diff --git a/gui/transferd_gui/wormhole/server.py b/gui/transferd_gui/wormhole/server.py new file mode 100644 index 0000000..dce99d5 --- /dev/null +++ b/gui/transferd_gui/wormhole/server.py @@ -0,0 +1,616 @@ +"""The wormhole mailbox server: holds encrypted messages for a nameplate until both sides have read them. + +It is a WebSocket server, served over TLS when it is on the network (`tls.py`). Every message is one JSON object. It sees +nameplates, side ids, phase names, sizes and timing. It never sees a code, a key, or the content of anything, because the +bodies are sealed by the clients. The wire protocol is described in `gui\\docs\\WORMHOLE.md`. + +It is meant to be left running and to be used by computers it does not know: +- every refusal carries a machine-readable `code`, and one that can be retried says after how many seconds, `retry_after`; +- each address is held to a rate for allocating, claiming and adding, so one computer cannot fill the mailbox; +- there are caps on nameplates, on connections and on connections from one address, so the mailbox has a size it cannot exceed; +- a connection that has not bound within `bind_timeout` seconds is closed, so idle sockets do not pile up; +- pings close a connection that has stopped answering, so its nameplate is not held by a dead socket. + +Run one for a user or a test: + + python -m transferd_gui.wormhole.server --host 127.0.0.1 --port 4470 + python -m transferd_gui.wormhole.server --host 0.0.0.0 --port 4470 --identity C:\\path\\to\\folder +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import re +import secrets +import ssl +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Dict, List, Mapping, Optional, Set, Tuple + +from websockets.asyncio.server import Server, ServerConnection, serve +from websockets.exceptions import ConnectionClosed + +from transferd_gui.wormhole import tls +from transferd_gui.wormhole.codes import NAMEPLATE_MAX, NAMEPLATE_MIN + +log = logging.getLogger("transferd.wormhole.mailbox") + +APP_ID = "transferd-wormhole/1" +PROTOCOL = 2 +MOODS = ("happy", "lonely", "errory", "scary") +NAMEPLATE_TTL_S = 300.0 +MAILBOX_IDLE_TTL_S = 3600.0 +MAX_MESSAGE_BYTES = 65536 +MAX_MESSAGES_PER_MAILBOX = 64 +MAX_NAMEPLATES = 4096 +MAX_CONNECTIONS = 1024 +MAX_CONNECTIONS_PER_ADDRESS = 64 +BIND_TIMEOUT_S = 30.0 +BUSY_RETRY_S = 5.0 +REAP_EVERY_S = 30.0 +ALLOCATE_TRIES = 1000 +#: Requests per address: kind -> (burst, tokens added per second). A burst is spent at once, then the rate applies. +DEFAULT_RATES: Dict[str, Tuple[float, float]] = { + "allocate": (30.0, 0.5), # thirty at once, then thirty a minute + "claim": (120.0, 2.0), + "add": (200.0, 50.0), +} +_HEX16 = re.compile(r"[0-9a-f]{16}") +_HEX4 = re.compile(r"[0-9a-f]{4}") +_PHASE = re.compile(r"[a-z]{1,16}") +_NAMEPLATE = re.compile(r"[0-9]{1,5}") +_LOOPBACK = {"127.0.0.1", "localhost", "::1"} + + +class Code: + """The machine-readable code on every refusal. A client decides what to do from the code, not from the words.""" + + BAD_REQUEST = "bad_request" + NOT_BOUND = "not_bound" + ALREADY_BOUND = "already_bound" + WRONG_APP = "wrong_app" + BAD_SIDE = "bad_side" + UNKNOWN_MESSAGE = "unknown_message" + BAD_NAMEPLATE = "bad_nameplate" + NO_NAMEPLATE = "no_nameplate" + CROWDED = "crowded" + NO_MAILBOX = "no_mailbox" + TOO_BIG = "too_big" + BAD_ID = "bad_id" + BAD_PHASE = "bad_phase" + BAD_BODY = "bad_body" + FULL = "full" + RATE_LIMITED = "rate_limited" + BUSY = "busy" + + +@dataclass +class _Stored: + message_id: str + side: str + phase: str + body: str # hex, exactly as the sender sent it + + +@dataclass +class _Mailbox: + mailbox_id: str + last_active: float + sides: Set[str] = field(default_factory=set) + closed: Set[str] = field(default_factory=set) + messages: List[_Stored] = field(default_factory=list) + keys_seen: Set[tuple] = field(default_factory=set) # (side, message id), so a retry is stored once + acked: Dict[str, Set[str]] = field(default_factory=dict) # side -> ids that side has acknowledged + live: Dict[str, ServerConnection] = field(default_factory=dict) # side -> the connection that has it open + + +@dataclass +class _Nameplate: + number: int + touched: float + mailbox: Optional[_Mailbox] = None + + +@dataclass +class _Connection: + address: str = "?" + side: Optional[str] = None + opened: Set[str] = field(default_factory=set) + + +@dataclass +class _Bucket: + tokens: float + updated: float + + +def _address_of(ws: ServerConnection) -> str: + remote = getattr(ws, "remote_address", None) + return str(remote[0]) if remote else "?" + + +class MailboxServer: + """The mailbox. `clock` is injectable so tests can move time; `reap()` removes what has expired.""" + + def __init__( + self, + *, + clock: Callable[[], float] = time.monotonic, + nameplate_ttl: float = NAMEPLATE_TTL_S, + mailbox_idle_ttl: float = MAILBOX_IDLE_TTL_S, + max_message_bytes: int = MAX_MESSAGE_BYTES, + max_messages: int = MAX_MESSAGES_PER_MAILBOX, + max_nameplates: int = MAX_NAMEPLATES, + max_connections: int = MAX_CONNECTIONS, + max_connections_per_address: int = MAX_CONNECTIONS_PER_ADDRESS, + bind_timeout: float = BIND_TIMEOUT_S, + rates: Optional[Mapping[str, Tuple[float, float]]] = None, + ) -> None: + self._clock = clock + self._nameplate_ttl = nameplate_ttl + self._mailbox_idle_ttl = mailbox_idle_ttl + self._max_message_bytes = max_message_bytes + self._max_messages = max_messages + self._max_nameplates = max_nameplates + self._max_connections = max_connections + self._max_per_address = max_connections_per_address + self._bind_timeout = bind_timeout + self._rates: Dict[str, Tuple[float, float]] = {**DEFAULT_RATES, **(rates or {})} + for kind, (burst, refill) in self._rates.items(): + if burst < 1 or refill <= 0: + raise ValueError(f"the rate for {kind} needs a burst of at least 1 and a positive refill") + self._plates: Dict[int, _Nameplate] = {} + self._boxes: Dict[str, _Mailbox] = {} + self._buckets: Dict[Tuple[str, str], _Bucket] = {} + self._connections = 0 + self._per_address: Dict[str, int] = {} + #: The mood each side closed with, in order. A count of what the mailbox saw; it holds no message content. + self.close_moods: List[str] = [] + self.secure = False + self._server: Optional[Server] = None + self._reaper: Optional[asyncio.Task] = None + + # ----- lifecycle -------------------------------------------------------------------------------- + + async def start(self, host: str = "127.0.0.1", port: int = 0, *, tls: Optional[ssl.SSLContext] = None) -> int: + """Listen on `host:port` (port 0 picks a free one), over TLS when `tls` is an SSL context. Returns the port.""" + self._server = await serve( + self._handle, + host, + port, + ssl=tls, + max_size=2 * self._max_message_bytes + 8192, + ping_interval=20, + ping_timeout=20, + close_timeout=5, + ) + self.secure = tls is not None + self._reaper = asyncio.get_running_loop().create_task(self._reap_forever()) + return self.port + + @property + def port(self) -> int: + assert self._server is not None, "start() first" + return int(self._server.sockets[0].getsockname()[1]) + + async def close(self) -> None: + if self._reaper is not None: + self._reaper.cancel() + try: + await self._reaper + except (asyncio.CancelledError, Exception): + pass + self._reaper = None + if self._server is not None: + self._server.close() + await self._server.wait_closed() + self._server = None + + async def _reap_forever(self) -> None: + while True: + await asyncio.sleep(REAP_EVERY_S) + self.reap() + + # ----- what is held ---------------------------------------------------------------------------- + + def open_mailboxes(self) -> int: + return len(self._boxes) + + def open_nameplates(self) -> int: + return len(self._plates) + + def open_connections(self) -> int: + return self._connections + + def reap(self) -> None: + """Remove nameplates that were never claimed in time, mailboxes idle for too long, and rate buckets that have + been unused long enough to be full again.""" + now = self._clock() + for number, plate in list(self._plates.items()): + if plate.mailbox is None and now - plate.touched > self._nameplate_ttl: + del self._plates[number] + for box_id, box in list(self._boxes.items()): + if now - box.last_active > self._mailbox_idle_ttl: + self._drop_box(box) + for key, bucket in list(self._buckets.items()): + if now - bucket.updated > 600.0: + del self._buckets[key] + + def _drop_box(self, box: _Mailbox) -> None: + self._boxes.pop(box.mailbox_id, None) + for number, plate in list(self._plates.items()): + if plate.mailbox is box: + del self._plates[number] + + def _take(self, address: str, kind: str) -> float: + """Spend one request of `kind` from `address`'s allowance. Returns 0.0 if it may proceed, or the seconds to wait.""" + burst, refill = self._rates[kind] + now = self._clock() + key = (address, kind) + bucket = self._buckets.get(key) + if bucket is None: + bucket = _Bucket(tokens=burst, updated=now) + self._buckets[key] = bucket + bucket.tokens = min(burst, bucket.tokens + (now - bucket.updated) * refill) + bucket.updated = now + if bucket.tokens >= 1.0: + bucket.tokens -= 1.0 + return 0.0 + return max(0.01, (1.0 - bucket.tokens) / refill) + + def _admit(self, address: str) -> bool: + return self._connections < self._max_connections and self._per_address.get(address, 0) < self._max_per_address + + def _count(self, address: str, delta: int) -> None: + self._connections += delta + left = self._per_address.get(address, 0) + delta + if left > 0: + self._per_address[address] = left + else: + self._per_address.pop(address, None) + + # ----- one connection -------------------------------------------------------------------------- + + async def _handle(self, ws: ServerConnection) -> None: + address = _address_of(ws) + if not self._admit(address): + log.info("refused a connection from %s: the mailbox is at its connection limit", address) + await self._error(ws, Code.BUSY, "the mailbox is busy; try again later", None, retry_after=BUSY_RETRY_S) + await ws.close(1013, "busy") + return + state = _Connection(address=address) + self._count(address, 1) + watchdog = asyncio.get_running_loop().call_later(self._bind_timeout, self._expire_unbound, ws, state) + try: + await self._send(ws, { + "type": "welcome", + "protocol": PROTOCOL, + "limits": { + "max_message_bytes": self._max_message_bytes, + "max_messages_per_mailbox": self._max_messages, + "bind_timeout_s": self._bind_timeout, + }, + }) + async for raw in ws: + try: + message = json.loads(raw) + except (TypeError, ValueError): + await self._error(ws, Code.BAD_REQUEST, "a message is a JSON object", None) + continue + if not isinstance(message, dict): + await self._error(ws, Code.BAD_REQUEST, "a message is a JSON object", None) + continue + await self._dispatch(ws, state, message) + except ConnectionClosed: + pass + finally: + watchdog.cancel() + self._disconnect(ws, state) + self._count(address, -1) + + def _expire_unbound(self, ws: ServerConnection, state: _Connection) -> None: + if state.side is None: + asyncio.ensure_future(ws.close(1008, "bind first")) + + def _disconnect(self, ws: ServerConnection, state: _Connection) -> None: + if state.side is None: + return + for box_id in state.opened: + box = self._boxes.get(box_id) + if box is not None and box.live.get(state.side) is ws: + del box.live[state.side] + + async def _dispatch(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + kind = message.get("type") + if kind == "bind": + await self._bind(ws, state, message) + return + if state.side is None: + await self._error(ws, Code.NOT_BOUND, "bind before anything else", kind) + return + handler = { + "allocate": self._allocate, + "claim": self._claim, + "release": self._release, + "open": self._open, + "add": self._add, + "ack": self._ack, + "close": self._close, + }.get(kind) + if handler is None: + await self._error(ws, Code.UNKNOWN_MESSAGE, f"unknown message '{kind}'", kind) + return + if kind in self._rates: + wait = self._take(state.address, kind) + if wait > 0: + message_id = message.get("id") if kind == "add" else None + await self._error( + ws, + Code.RATE_LIMITED, + f"too many {kind} requests from this computer; try again in {wait:.2f} s", + kind, + message_id=message_id if isinstance(message_id, str) else None, + retry_after=wait, + ) + return + await handler(ws, state, message) + + async def _bind(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + if state.side is not None: + await self._error(ws, Code.ALREADY_BOUND, "already bound", "bind") + return + if message.get("appid") != APP_ID: + await self._error(ws, Code.WRONG_APP, f"this mailbox serves {APP_ID}", "bind") + return + side = message.get("side") + if not isinstance(side, str) or not _HEX16.fullmatch(side): + await self._error(ws, Code.BAD_SIDE, "a side id is 16 lower-case hex characters", "bind") + return + state.side = side + + async def _allocate(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + if len(self._plates) >= self._max_nameplates: + await self._error(ws, Code.BUSY, "this mailbox holds as many codes as it allows; try again later", "allocate", retry_after=BUSY_RETRY_S) + return + now = self._clock() + for _ in range(ALLOCATE_TRIES): + number = secrets.randbelow(NAMEPLATE_MAX - NAMEPLATE_MIN + 1) + NAMEPLATE_MIN + if number not in self._plates: + self._plates[number] = _Nameplate(number, now) + await self._send(ws, {"type": "allocated", "nameplate": str(number)}) + return + await self._error(ws, Code.NO_NAMEPLATE, "no nameplate is free; try again later", "allocate", retry_after=BUSY_RETRY_S) + + async def _claim(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + number = self._nameplate_of(message.get("nameplate")) + if number is None: + await self._error(ws, Code.BAD_NAMEPLATE, "a nameplate is a number", "claim") + return + now = self._clock() + plate = self._plates.get(number) + if plate is None: + if len(self._plates) >= self._max_nameplates: + await self._error(ws, Code.BUSY, "this mailbox holds as many codes as it allows; try again later", "claim", retry_after=BUSY_RETRY_S) + return + plate = _Nameplate(number, now) + self._plates[number] = plate + plate.touched = now + if plate.mailbox is None: + plate.mailbox = _Mailbox(secrets.token_hex(16), now) + self._boxes[plate.mailbox.mailbox_id] = plate.mailbox + box = plate.mailbox + if state.side not in box.sides: + if len(box.sides) >= 2: + await self._error(ws, Code.CROWDED, "crowded: this code is already used by two computers", "claim") + return + box.sides.add(state.side) + box.last_active = now + await self._send(ws, {"type": "claimed", "mailbox": box.mailbox_id}) + + async def _release(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + number = self._nameplate_of(message.get("nameplate")) + if number is None: + await self._error(ws, Code.BAD_NAMEPLATE, "a nameplate is a number", "release") + return + plate = self._plates.get(number) + if plate is not None and plate.mailbox is not None: + box = plate.mailbox + box.sides.discard(state.side) + box.closed.discard(state.side) + box.live.pop(state.side, None) + if not box.sides: + self._drop_box(box) + elif plate is not None: + del self._plates[number] + await self._send(ws, {"type": "released"}) + + async def _open(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + box = await self._member_box(ws, state, message, "open") + if box is None: + return + box.live[state.side] = ws + state.opened.add(box.mailbox_id) + box.last_active = self._clock() + acked = box.acked.get(state.side, set()) + for stored in list(box.messages): + if stored.side == state.side or stored.message_id in acked: + continue + await self._send(ws, self._message_for(box, stored)) + await self._send(ws, {"type": "opened", "mailbox": box.mailbox_id}) + + async def _add(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + box = await self._member_box(ws, state, message, "add") + if box is None: + return + message_id = message.get("id") + phase = message.get("phase") + body = message.get("body") + if not isinstance(message_id, str) or not _HEX4.fullmatch(message_id): + await self._error(ws, Code.BAD_ID, "a message id is 4 hex characters", "add") + return + if not isinstance(phase, str) or not _PHASE.fullmatch(phase): + await self._error(ws, Code.BAD_PHASE, "a phase is 1 to 16 lower-case letters", "add", message_id) + return + if not isinstance(body, str): + await self._error(ws, Code.BAD_BODY, "a body is hex text", "add", message_id) + return + try: + raw = bytes.fromhex(body) + except ValueError: + await self._error(ws, Code.BAD_BODY, "a body is hex text", "add", message_id) + return + if len(raw) > self._max_message_bytes: + await self._error(ws, Code.TOO_BIG, f"a message is at most {self._max_message_bytes} bytes", "add", message_id) + return + box.last_active = self._clock() + if (state.side, message_id) in box.keys_seen: + # A retry of a message already stored: confirm it, store nothing. + await self._send(ws, {"type": "added", "id": message_id}) + return + if len(box.messages) >= self._max_messages: + await self._error(ws, Code.FULL, "this mailbox is full", "add", message_id) + return + box.keys_seen.add((state.side, message_id)) + stored = _Stored(message_id, state.side, phase, body.lower()) + box.messages.append(stored) + await self._send(ws, {"type": "added", "id": message_id}) + for side, peer in list(box.live.items()): + if side != state.side: + await self._send_quietly(peer, self._message_for(box, stored)) + + async def _ack(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + box = await self._member_box(ws, state, message, "ack") + if box is None: + return + message_id = message.get("id") + if isinstance(message_id, str) and _HEX4.fullmatch(message_id): + box.acked.setdefault(state.side, set()).add(message_id) + box.last_active = self._clock() + + async def _close(self, ws: ServerConnection, state: _Connection, message: dict) -> None: + box = await self._member_box(ws, state, message, "close") + if box is None: + return + mood = message.get("mood", "happy") + if mood not in MOODS: + mood = "happy" + log.info("mailbox %s: side closed (%s)", box.mailbox_id[:8], mood) + self.close_moods.append(mood) + box.closed.add(state.side) + box.live.pop(state.side, None) + state.opened.discard(box.mailbox_id) + await self._send(ws, {"type": "closed"}) + if box.sides and box.sides <= box.closed: + self._drop_box(box) + + # ----- helpers --------------------------------------------------------------------------------- + + async def _member_box(self, ws: ServerConnection, state: _Connection, message: dict, kind: str) -> Optional[_Mailbox]: + box_id = message.get("mailbox") + box = self._boxes.get(box_id) if isinstance(box_id, str) else None + if box is None or state.side not in box.sides: + await self._error(ws, Code.NO_MAILBOX, "no such mailbox for this side", kind) + return None + return box + + @staticmethod + def _nameplate_of(value) -> Optional[int]: + if not isinstance(value, str) or not _NAMEPLATE.fullmatch(value): + return None + number = int(value) + if not NAMEPLATE_MIN <= number <= NAMEPLATE_MAX: + return None + return number + + @staticmethod + def _message_for(box: _Mailbox, stored: _Stored) -> dict: + return { + "type": "message", + "mailbox": box.mailbox_id, + "id": stored.message_id, + "side": stored.side, + "phase": stored.phase, + "body": stored.body, + } + + @staticmethod + async def _send(ws: ServerConnection, message: dict) -> None: + await ws.send(json.dumps(message, separators=(",", ":"))) + + @staticmethod + async def _send_quietly(ws: ServerConnection, message: dict) -> None: + try: + await MailboxServer._send(ws, message) + except ConnectionClosed: + pass + + @staticmethod + async def _error( + ws: ServerConnection, + code: str, + text: str, + orig: Optional[str], + message_id: Optional[str] = None, + retry_after: Optional[float] = None, + ) -> None: + reply: dict = {"type": "error", "code": code, "error": text, "orig": orig} + if message_id is not None: + reply["id"] = message_id + if retry_after is not None: + reply["retry_after"] = round(float(retry_after), 3) + await MailboxServer._send(ws, reply) + + +async def run_forever(host: str, port: int, identity_dir: Optional[str] = None) -> None: + """Serve until interrupted. With `identity_dir`, the mailbox is served over TLS with the certificate kept there.""" + context = None + fingerprint = "" + if identity_dir: + identity = tls.load_or_create(Path(identity_dir)) + context = tls.server_context(identity) + fingerprint = identity.fingerprint + server = MailboxServer() + bound = await server.start(host, port, tls=context) + scheme = "wss" if context is not None else "ws" + log.info("mailbox listening on %s://%s:%d", scheme, host, bound) + print(f"Transferd wormhole mailbox listening on {scheme}://{host}:{bound}", flush=True) + if fingerprint: + print(f"Its fingerprint, to pin in the other computers' settings: {fingerprint}", flush=True) + try: + await asyncio.Event().wait() + finally: + await server.close() + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(description="Run a Transferd wormhole mailbox.") + parser.add_argument("--host", default="127.0.0.1", help="address to listen on (default 127.0.0.1, this computer only)") + parser.add_argument("--port", type=int, default=4470, help="port to listen on (default 4470)") + parser.add_argument( + "--identity", + metavar="FOLDER", + help="folder for the mailbox's certificate and key, made on first run; serves wss:// with a pinned certificate", + ) + args = parser.parse_args(argv) + if args.host not in _LOOPBACK and not args.identity: + print( + "a mailbox that other computers can reach must be served over TLS: give --identity FOLDER, " + "or keep --host 127.0.0.1", + file=sys.stderr, + ) + return 2 + logging.basicConfig(level=logging.INFO) + try: + asyncio.run(run_forever(args.host, args.port, args.identity)) + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/gui/transferd_gui/wormhole/session.py b/gui/transferd_gui/wormhole/session.py new file mode 100644 index 0000000..672426f --- /dev/null +++ b/gui/transferd_gui/wormhole/session.py @@ -0,0 +1,381 @@ +"""One wormhole attempt, from both ends: the sender's side and the receiver's side, as two state machines. + + sender: start() -> the code to show; run() -> sends pake, version, identity, offer; then the transfer; then done + receiver: connect(code) -> pake, version, identity; offer() -> what is offered; answer(accept); finish(folder) + +Each phase is one message from each side, and the order is fixed. A phase that does not arrive in time raises `TimedOut`; +a phase that does not open raises `OpenError` (the code is wrong, or the message was changed); a phase that is not what the +protocol allows raises `ProtocolError`. Every attempt ends by closing its mailbox with a mood: `happy`, `lonely` (the other +side never came), `scary` (the code was wrong), or `errory`. + +The transfer itself is the `Transit` the caller gives. The overlay implementation is `endpoint.OverlayTransit`; tests use a +transit that keeps the bytes in memory. +""" + +from __future__ import annotations + +import asyncio +import tempfile +from dataclasses import dataclass +from pathlib import Path +from typing import Callable, Dict, Optional, Protocol + +from transferd_gui.wormhole import keys, protocol as P, transfer +from transferd_gui.wormhole.codes import Code, generate +from transferd_gui.wormhole.errors import ( + MailboxError, + OpenError, + ProtocolError, + TimedOut, + TransferError, + WormholeError, +) +from transferd_gui.wormhole.keys import Pake, open_sealed, seal +from transferd_gui.wormhole.mailbox import Incoming, MailboxClient + +PHASE_TIMEOUT_S = 120.0 +PAKE_TIMEOUT_S = 60.0 +ANSWER_TIMEOUT_S = 600.0 + + +class Transit(Protocol): + """Moves a file over the overlay, once both sides have agreed to it. The session calls it only after `accept`.""" + + def local_identity(self) -> P.PeerIdentity: + """This side's identity for the attempt, with the places to reach it. Valid after `open`.""" + + def expect_peer(self, peer: P.PeerIdentity) -> None: + """The other side's identity has been read and checked. Only that identity may connect from now on.""" + + async def open(self) -> None: + """Start listening and, if a relay is set, register with it. Called before the identities are sent.""" + + async def send(self, peer: P.PeerIdentity, offer: P.Offer, source: Path) -> None: + """Send `source` to the peer.""" + + async def receive(self, peer: P.PeerIdentity, offer: P.Offer, folder: Path) -> Path: + """Receive the file the offer describes into `folder`, and return where it was written.""" + + async def close(self) -> None: + """Stop listening and drop every connection of this attempt.""" + + +@dataclass(frozen=True) +class SendResult: + ok: bool + reason: str = "" + declined: bool = False + + +@dataclass(frozen=True) +class ReceiveResult: + kind: str + path: Optional[Path] = None + text: str = "" + sha256: str = "" + + +class _Exchange: + """What both sides share: the mailbox, the keys once they exist, and the buffer of phases that came early.""" + + def __init__(self, mailbox_url: str, side: str, transit: Transit, on_state: Optional[Callable[[str], None]]) -> None: + self.side = keys.check_side(side) + self.mailbox = MailboxClient(mailbox_url, self.side) + self.transit = transit + self._say = on_state or (lambda text: None) + self._keys: Optional[keys.Keys] = None + self._peer: Optional[str] = None + self._buffer: Dict[str, Incoming] = {} + + def _state(self, text: str) -> None: + self._say(text) + + async def _reconnect(self) -> None: + await self.mailbox.reconnect() + await self.mailbox.flush() + + async def _next(self, phase: str, timeout: float) -> Incoming: + """The next message of `phase` from the other side. Other phases that arrive first are kept for later.""" + if phase in self._buffer: + return self._buffer.pop(phase) + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while True: + if not self.mailbox.connected: + try: + await self._reconnect() + except MailboxError: + pass + remaining = deadline - loop.time() + if remaining <= 0: + raise TimedOut(f"the other computer did not send '{phase}' in time") + incoming = await self.mailbox.receive(min(remaining, 1.0)) + if incoming is None: + continue + if self._peer is not None and incoming.side != self._peer: + await self.mailbox.ack(incoming.message_id) + continue + if incoming.phase == phase: + return incoming + self._buffer.setdefault(incoming.phase, incoming) + + async def _send_sealed(self, phase: str, message: Dict) -> None: + if self._keys is None: + raise ProtocolError("the key exchange has not finished") + message_id = keys.new_message_id() + body = seal(self._keys, self.side, phase, message_id, P.encode(message)) + try: + await self.mailbox.add(phase, body, message_id=message_id) + except MailboxError: + await self._reconnect() + + async def _recv_sealed(self, phase: str, timeout: Optional[float] = None) -> Dict: + if self._keys is None: + raise ProtocolError("the key exchange has not finished") + incoming = await self._next(phase, PHASE_TIMEOUT_S if timeout is None else timeout) + plain = open_sealed(self._keys, incoming.side, phase, incoming.message_id, incoming.body) + await self.mailbox.ack(incoming.message_id) + return P.decode(plain) + + async def _send_pake(self, pake: Pake) -> None: + try: + await self.mailbox.add("pake", pake.outbound) + except MailboxError: + await self._reconnect() + + async def _agree(self, pake: Pake) -> None: + """Send our pake, read theirs, and derive the keys. A malformed one is refused.""" + await self._send_pake(pake) + incoming = await self._next("pake", PAKE_TIMEOUT_S) + self._peer = incoming.side + await self.mailbox.ack(incoming.message_id) + self._keys = pake.finish(incoming.body) + + async def _versions(self) -> None: + await self._send_sealed("version", P.Version.ours().to_dict()) + version = P.Version.from_dict(await self._recv_sealed("version")) + version.check() + + async def _identities(self) -> P.PeerIdentity: + await self.transit.open() + await self._send_sealed("identity", self.transit.local_identity().to_dict()) + peer = P.PeerIdentity.from_dict(await self._recv_sealed("identity")) + self.transit.expect_peer(peer) + return peer + + async def _end(self, mood: str) -> None: + try: + await self.mailbox.close(mood) + except MailboxError: + pass + try: + await self.transit.close() + except Exception: + pass + + @staticmethod + def _mood_for(error: BaseException) -> str: + if isinstance(error, OpenError): + return "scary" + if isinstance(error, TimedOut): + return "lonely" + return "errory" + + +class Sender(_Exchange): + """The side that has something to send. It shows the code, then waits for the other side to type it.""" + + def __init__( + self, + mailbox_url: str, + *, + transit: Transit, + offer: P.Offer, + source: Optional[Path] = None, + on_state: Optional[Callable[[str], None]] = None, + answer_timeout: float = ANSWER_TIMEOUT_S, + ) -> None: + super().__init__(mailbox_url, keys.new_side(), transit, on_state) + self.offer = offer + self.source = source + self.code: Optional[Code] = None + self._pake: Optional[Pake] = None + self._answer_timeout = answer_timeout + + async def start(self) -> Code: + """Connect, reserve a nameplate, and return the code to show. Safe to call once.""" + if self.code is not None: + return self.code + if self.offer.kind != "text" and self.source is None: + raise ProtocolError("a file or folder offer needs its source") + try: + self._state("Connecting to the mailbox") + await self.mailbox.connect() + nameplate = await self.mailbox.allocate() + await self.mailbox.claim(nameplate) + await self.mailbox.open() + except BaseException: + await self._end("errory") + raise + self.code = generate(nameplate) + self._pake = Pake(self.code.password()) + self._state("Waiting for the other computer to type the code") + return self.code + + async def run(self) -> SendResult: + if self.code is None or self._pake is None: + raise ProtocolError("start() before run()") + try: + self._state("Exchanging keys") + await self._agree(self._pake) + await self._versions() + self._state("Exchanging connection details") + peer = await self._identities() + self._state("Waiting for the other computer to accept") + await self._send_sealed("offer", self.offer.to_dict()) + answer = P.Answer.from_dict(await self._recv_sealed("answer", self._answer_timeout)) + if not answer.accept: + await self._end("happy") + return SendResult(False, answer.reason or "the other computer declined", declined=True) + if self.offer.kind != "text": + self._state("Sending") + await self.transit.send(peer, self.offer, self.source) # type: ignore[arg-type] + done = P.Done.from_dict(await self._recv_sealed("done")) + if not done.ok: + raise TransferError(done.reason or "the other computer did not accept the transfer") + await self._end("happy") + self._state("Sent") + return SendResult(True) + except WormholeError as exc: + await self._end(self._mood_for(exc)) + raise + except BaseException: + await self._end("errory") + raise + + async def abandon(self) -> None: + """Stop before the other side has come: the code stops working and the mailbox is closed.""" + await self._end("lonely") + + +class Receiver(_Exchange): + """The side that types a code. It reads what is offered, and only then the user decides.""" + + def __init__( + self, + mailbox_url: str, + code: Code, + *, + transit: Transit, + on_state: Optional[Callable[[str], None]] = None, + ) -> None: + super().__init__(mailbox_url, keys.new_side(), transit, on_state) + self.code = code + self.offer_received: Optional[P.Offer] = None + self.peer: Optional[P.PeerIdentity] = None + self._accepted = False + + async def connect(self) -> None: + """Join the code's mailbox and make the keys. Refused if the code is wrong, once the first sealed phase is read.""" + try: + self._state("Connecting to the mailbox") + await self.mailbox.connect() + await self.mailbox.claim(self.code.nameplate) + await self.mailbox.open() + self._state("Exchanging keys") + await self._agree(Pake(self.code.password())) + await self._versions() + self._state("Exchanging connection details") + self.peer = await self._identities() + except WormholeError as exc: + await self._end(self._mood_for(exc)) + raise + except BaseException: + await self._end("errory") + raise + + async def offer(self) -> P.Offer: + """What the other side is offering. The caller shows it and then calls `answer`.""" + if self.peer is None: + raise ProtocolError("connect() first") + try: + self._state("Waiting for the offer") + self.offer_received = P.Offer.from_dict(await self._recv_sealed("offer")) + return self.offer_received + except WormholeError as exc: + await self._end(self._mood_for(exc)) + raise + except BaseException: + await self._end("errory") + raise + + async def answer(self, accept: bool, reason: str = "") -> None: + if self.offer_received is None: + raise ProtocolError("offer() first") + self._accepted = bool(accept) + await self._send_sealed("answer", P.Answer(bool(accept), reason).to_dict()) + + async def finish(self, folder: Path) -> ReceiveResult: + """Receive what was accepted into `folder`, check it, and tell the sender how it went. + + The bytes arrive in a hidden staging folder inside `folder`. Only a file that has checked is placed, under a name + that does not exist yet; a folder is unpacked from its checked archive. Nothing else is left in `folder`.""" + if self.offer_received is None: + raise ProtocolError("offer() first") + offer = self.offer_received + if not self._accepted: + await self._end("happy") + return ReceiveResult("declined") + try: + if offer.kind == "text": + await self._send_sealed("done", P.Done(True).to_dict()) + await self._end("happy") + return ReceiveResult("text", None, offer.text, offer.sha256) + self._state("Receiving") + assert self.peer is not None + folder.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=".wormhole-", dir=folder)) + try: + received = await self.transit.receive(self.peer, offer, staging) + checked = self._verified(received, offer) + if offer.kind == "directory": + path = transfer.unpack_folder(checked, folder, offer.name, expected_entries=offer.entries) + else: + path = transfer.place_file(checked, folder, offer.name) + finally: + transfer.remove_quietly(staging) + await self._send_sealed("done", P.Done(True, sha256=offer.sha256).to_dict()) + await self._end("happy") + self._state("Received") + return ReceiveResult(offer.kind, path, "", offer.sha256) + except WormholeError as exc: + await self._send_quietly("done", P.Done(False, reason=str(exc)[:200]).to_dict()) + await self._end(self._mood_for(exc)) + raise + except BaseException: + await self._send_quietly("done", P.Done(False, reason="the transfer failed").to_dict()) + await self._end("errory") + raise + + async def _send_quietly(self, phase: str, message: Dict) -> None: + try: + await self._send_sealed(phase, message) + except WormholeError: + pass + + async def abandon(self) -> None: + """Stop while the offer waits for the user. An offer that was read is declined, so the sender is told, then the + attempt is closed. Before an offer is read there is nothing to decline.""" + if self.offer_received is not None and not self._accepted: + await self._send_quietly("answer", P.Answer(False, "stopped by the receiving user").to_dict()) + await self._end("happy" if self.peer is not None else "lonely") + + @staticmethod + def _verified(received: Path, offer: P.Offer) -> Path: + """The received bytes are checked against the offer's hash before anything is made of them.""" + if not received.is_file() or transfer.sha256_file(received) != offer.sha256: + raise TransferError("the received data does not match what was offered") + return received + + +__all__ = ["ANSWER_TIMEOUT_S", "PHASE_TIMEOUT_S", "Receiver", "ReceiveResult", "SendResult", "Sender", "Transit"] diff --git a/gui/transferd_gui/wormhole/tls.py b/gui/transferd_gui/wormhole/tls.py new file mode 100644 index 0000000..f841eb9 --- /dev/null +++ b/gui/transferd_gui/wormhole/tls.py @@ -0,0 +1,160 @@ +"""TLS for the mailbox: the certificate a mailbox makes for itself, and the pin a client holds it to. + +A mailbox on the network serves wss://. Its certificate is made once, on the computer that hosts the mailbox, and kept in the +wormhole folder. Its SHA-256 fingerprint is the pin. A client given that fingerprint (copied from the hosting computer into +Settings) accepts that certificate and no other. A mailbox run by someone else with a certificate from a public authority +needs no pin: the system's certificates are checked as usual. + +The pin does not depend on names. The TLS handshake still proves that the server holds the private key of the pinned +certificate, and the fingerprint is compared before anything is sent. Message content is sealed by the two clients whatever the +transport does. So TLS here keeps the nameplates, timing and sizes from the network, and keeps a stranger from standing in +for the mailbox. +""" + +from __future__ import annotations + +import datetime +import hashlib +import os +import ssl +from dataclasses import dataclass +from pathlib import Path + +CERT_FILE = "mailbox-cert.pem" +KEY_FILE = "mailbox-key.pem" +VALID_DAYS = 3650 +#: A certificate this close to its end is replaced the next time the mailbox starts. +RENEW_BEFORE_DAYS = 30 +COMMON_NAME = "Transferd wormhole mailbox" +MIN_TLS = ssl.TLSVersion.TLSv1_2 + + +@dataclass(frozen=True) +class Identity: + """The mailbox's certificate and key, on disk, and the fingerprint of the certificate.""" + + cert_path: Path + key_path: Path + fingerprint: str # lower-case hex SHA-256 of the DER certificate + + +def fingerprint_of(der: bytes) -> str: + return hashlib.sha256(der).hexdigest() + + +def load_or_create(directory: Path) -> Identity: + """The identity in `directory`. Made on first use, and again when the files are missing, do not match, or are near expiry.""" + directory.mkdir(parents=True, exist_ok=True) + cert_path = directory / CERT_FILE + key_path = directory / KEY_FILE + if not _usable(cert_path, key_path): + cert_pem, key_pem = _make() + # The key is written first. A crash between the two writes leaves a pair that does not match, which is made again. + _write_private(key_path, key_pem) + _write_atomic(cert_path, cert_pem) + der = ssl.PEM_cert_to_DER_cert(cert_path.read_text(encoding="ascii")) + return Identity(cert_path, key_path, fingerprint_of(der)) + + +def server_context(identity: Identity) -> ssl.SSLContext: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = MIN_TLS + context.load_cert_chain(str(identity.cert_path), str(identity.key_path)) + return context + + +def pinned_context() -> ssl.SSLContext: + """For a mailbox held to a pin. The chain is not checked, since a self-made certificate has no chain to check. The client + compares the fingerprint after the handshake and before it sends anything; see `peer_fingerprint`.""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.minimum_version = MIN_TLS + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + +def system_context() -> ssl.SSLContext: + """For a mailbox with no pin: the system's certificates, and the host name, are checked.""" + context = ssl.create_default_context() + context.minimum_version = MIN_TLS + return context + + +def peer_fingerprint(ws) -> str: + """The fingerprint of the certificate a connected websocket's server presented, or "" if there is none (a plain connection).""" + transport = getattr(ws, "transport", None) + ssl_object = transport.get_extra_info("ssl_object") if transport is not None else None + if ssl_object is None: + return "" + der = ssl_object.getpeercert(binary_form=True) + return fingerprint_of(der) if der else "" + + +# ----- making and keeping the identity ------------------------------------------------------------------- + + +def _usable(cert_path: Path, key_path: Path) -> bool: + if not (cert_path.is_file() and key_path.is_file()): + return False + from cryptography import x509 + from cryptography.hazmat.primitives import serialization + + try: + cert = x509.load_pem_x509_certificate(cert_path.read_bytes()) + key = serialization.load_pem_private_key(key_path.read_bytes(), password=None) + except (ValueError, TypeError, OSError): + return False + now = datetime.datetime.now(datetime.timezone.utc) + if cert.not_valid_after_utc - now < datetime.timedelta(days=RENEW_BEFORE_DAYS): + return False + spki = serialization.PublicFormat.SubjectPublicKeyInfo + der = serialization.Encoding.DER + return cert.public_key().public_bytes(der, spki) == key.public_key().public_bytes(der, spki) + + +def _make() -> "tuple[bytes, bytes]": + import ipaddress + + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID + + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, COMMON_NAME)]) + now = datetime.datetime.now(datetime.timezone.utc) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=VALID_DAYS)) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension( + x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + cert_pem = cert.public_bytes(serialization.Encoding.PEM) + key_pem = key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + ) + return cert_pem, key_pem + + +def _write_private(path: Path, data: bytes) -> None: + """Write a secret file: owner-only where the platform allows it. On Windows the folder's own permissions apply.""" + _write_atomic(path, data) + try: + os.chmod(path, 0o600) + except OSError: + pass + + +def _write_atomic(path: Path, data: bytes) -> None: + tmp = path.with_name(path.name + ".tmp") + tmp.write_bytes(data) + os.replace(tmp, path) diff --git a/gui/transferd_gui/wormhole/transfer.py b/gui/transferd_gui/wormhole/transfer.py new file mode 100644 index 0000000..2fc3de6 --- /dev/null +++ b/gui/transferd_gui/wormhole/transfer.py @@ -0,0 +1,163 @@ +"""Files and folders for a wormhole: hashing, zipping a folder to send, and unpacking a received folder safely. + +A folder is sent as one zip archive. The receiver checks the archive's hash against the offer, and only then unpacks it, +and it unpacks it under the rules in `gui\\docs\\WORMHOLE.md`: no absolute or `..` names, no links or devices, a limit on the +number of entries and on the total size, and a limit on how well the archive compresses. +""" + +from __future__ import annotations + +import hashlib +import re +import shutil +import stat +import zipfile +from pathlib import Path +from typing import Tuple + +from transferd_gui.backend.files import unique_path +from transferd_gui.wormhole import protocol as P +from transferd_gui.wormhole.errors import TransferError + +CHUNK = 256 * 1024 +UNPACKED_MAX = 10 * 1024 ** 3 +RATIO_MAX = 100 +RATIO_FREE_BYTES = 1024 * 1024 +_BAD_PART = re.compile(r'[\x00-\x1f<>:"\\|?*]') + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(CHUNK), b""): + digest.update(block) + return digest.hexdigest() + + +def remove_quietly(path: Path) -> None: + try: + if path.is_dir(): + shutil.rmtree(path, ignore_errors=True) + else: + path.unlink() + except OSError: + pass + + +def unique_folder(parent: Path, name: str) -> Path: + """`parent/name`, or `name (2)`, `name (3)` and so on, whichever does not exist yet. Created by the caller.""" + candidate = parent / name + counter = 2 + while candidate.exists(): + candidate = parent / f"{name} ({counter})" + counter += 1 + return candidate + + +def place_file(source: Path, folder: Path, name: str) -> Path: + """Move a checked file into `folder` under its offered name, or the next free name. Returns where it went.""" + target = unique_path(folder, P.safe_offered_name(name)) + shutil.move(str(source), str(target)) + return target + + +# ----- sending ---------------------------------------------------------------------------------------- + + +def prepare_file(path: Path) -> Tuple[P.Offer, Path]: + """The offer for one file, with its size and hash, and the file itself.""" + if not path.is_file(): + raise TransferError(f"{path.name} is not a file") + return P.Offer.for_file(path.name, path.stat().st_size, sha256_file(path)), path + + +def zip_folder(folder: Path, archive: Path) -> int: + """Zip a folder into `archive`. Links and anything that is not a file or a folder are refused. Returns the entry count.""" + entries = 0 + with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for path in sorted(folder.rglob("*")): + if path.is_symlink(): + raise TransferError(f"{path.name} is a link; links are not sent") + relative = path.relative_to(folder).as_posix() + if path.is_dir(): + zf.writestr(relative + "/", b"") + elif path.is_file(): + zf.write(path, relative) + else: + raise TransferError(f"{path.name} is neither a file nor a folder") + entries += 1 + if entries > P.ENTRIES_MAX: + raise TransferError(f"a folder can have at most {P.ENTRIES_MAX} entries") + return entries + + +def prepare_folder(folder: Path, scratch: Path) -> Tuple[P.Offer, Path]: + """Zip a folder into `scratch` and return its offer and the archive.""" + if not folder.is_dir(): + raise TransferError(f"{folder.name} is not a folder") + archive = scratch / (re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", folder.name).strip(" .") + ".zip") + entries = zip_folder(folder, archive) + return P.Offer.for_directory(folder.name, archive.stat().st_size, sha256_file(archive), entries), archive + + +# ----- receiving -------------------------------------------------------------------------------------- + + +def _member_refused(info: zipfile.ZipInfo) -> str: + """Why an archive member must not be unpacked, or the empty string if it may be.""" + name = info.filename + # Windows rewrites backslashes while reading, so the name as written is checked too. + raw = getattr(info, "orig_filename", name) + if "\\" in raw or raw.startswith("/") or name.startswith("/"): + return "an entry has an absolute or backslash path" + parts = name.rstrip("/").split("/") + if any(part in ("", ".", "..") for part in parts): + return "an entry has an empty, '.' or '..' part" + if any(_BAD_PART.search(part) for part in parts): + return "an entry name has a character a file name cannot have" + mode = (info.external_attr >> 16) & 0o170000 + if mode == stat.S_IFLNK: + return "an entry is a link" + if mode not in (0, stat.S_IFREG, stat.S_IFDIR): + return "an entry is not a file or a folder" + return "" + + +def unpack_folder(archive: Path, parent: Path, name: str, *, expected_entries: int) -> Path: + """Unpack a checked archive into a new folder under `parent`. Refuses an unsafe archive and leaves nothing behind.""" + target = unique_folder(parent, P.safe_offered_name(name)) + target.mkdir(parents=True) + try: + with zipfile.ZipFile(archive) as zf: + infos = zf.infolist() + if len(infos) != expected_entries: + raise TransferError("the folder does not hold the number of entries that was offered") + compressed = max(1, sum(info.compress_size for info in infos)) + total = 0 + root = target.resolve() + for info in infos: + reason = _member_refused(info) + if reason: + raise TransferError(f"the folder was refused: {reason}") + destination = target.joinpath(*info.filename.rstrip("/").split("/")).resolve() + if root not in destination.parents and destination != root: + raise TransferError("the folder was refused: an entry leaves it") + if info.is_dir(): + destination.mkdir(parents=True, exist_ok=True) + continue + destination.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as source, open(destination, "xb") as out: + for block in iter(lambda: source.read(CHUNK), b""): + total += len(block) + if total > UNPACKED_MAX: + raise TransferError("the folder is larger than the limit") + if total > RATIO_FREE_BYTES and total > RATIO_MAX * compressed: + raise TransferError("the folder compresses too well to be a folder; it was refused") + out.write(block) + except (zipfile.BadZipFile, OSError) as exc: + remove_quietly(target) + raise TransferError("the folder could not be unpacked") from exc + except TransferError: + remove_quietly(target) + raise + return target diff --git a/gui/transferd_gui/wormhole/wordlist.py b/gui/transferd_gui/wormhole/wordlist.py new file mode 100644 index 0000000..79f8589 --- /dev/null +++ b/gui/transferd_gui/wormhole/wordlist.py @@ -0,0 +1,534 @@ +"""The PGP word list, used to spell a wormhole's secret words. + +Each byte has two words: one from the even list and one from the odd list. A code alternates the lists by +position, so a dropped or swapped word is noticed when the code is read back. The lists are the PGP word +list (https://en.wikipedia.org/wiki/PGP_Words), transcribed by Warren Guy and taken from magic-wormhole +(MIT licence, https://github.com/magic-wormhole/magic-wormhole). The words are lower case here; the code is +case-insensitive. +""" + +from __future__ import annotations + +#: Index is the byte value; the word for an even position. +EVEN_WORDS = ( + "aardvark", + "absurd", + "accrue", + "acme", + "adrift", + "adult", + "afflict", + "ahead", + "aimless", + "algol", + "allow", + "alone", + "ammo", + "ancient", + "apple", + "artist", + "assume", + "athens", + "atlas", + "aztec", + "baboon", + "backfield", + "backward", + "banjo", + "beaming", + "bedlamp", + "beehive", + "beeswax", + "befriend", + "belfast", + "berserk", + "billiard", + "bison", + "blackjack", + "blockade", + "blowtorch", + "bluebird", + "bombast", + "bookshelf", + "brackish", + "breadline", + "breakup", + "brickyard", + "briefcase", + "burbank", + "button", + "buzzard", + "cement", + "chairlift", + "chatter", + "checkup", + "chisel", + "choking", + "chopper", + "christmas", + "clamshell", + "classic", + "classroom", + "cleanup", + "clockwork", + "cobra", + "commence", + "concert", + "cowbell", + "crackdown", + "cranky", + "crowfoot", + "crucial", + "crumpled", + "crusade", + "cubic", + "dashboard", + "deadbolt", + "deckhand", + "dogsled", + "dragnet", + "drainage", + "dreadful", + "drifter", + "dropper", + "drumbeat", + "drunken", + "dupont", + "dwelling", + "eating", + "edict", + "egghead", + "eightball", + "endorse", + "endow", + "enlist", + "erase", + "escape", + "exceed", + "eyeglass", + "eyetooth", + "facial", + "fallout", + "flagpole", + "flatfoot", + "flytrap", + "fracture", + "framework", + "freedom", + "frighten", + "gazelle", + "geiger", + "glitter", + "glucose", + "goggles", + "goldfish", + "gremlin", + "guidance", + "hamlet", + "highchair", + "hockey", + "indoors", + "indulge", + "inverse", + "involve", + "island", + "jawbone", + "keyboard", + "kickoff", + "kiwi", + "klaxon", + "locale", + "lockup", + "merit", + "minnow", + "miser", + "mohawk", + "mural", + "music", + "necklace", + "neptune", + "newborn", + "nightbird", + "oakland", + "obtuse", + "offload", + "optic", + "orca", + "payday", + "peachy", + "pheasant", + "physique", + "playhouse", + "pluto", + "preclude", + "prefer", + "preshrunk", + "printer", + "prowler", + "pupil", + "puppy", + "python", + "quadrant", + "quiver", + "quota", + "ragtime", + "ratchet", + "rebirth", + "reform", + "regain", + "reindeer", + "rematch", + "repay", + "retouch", + "revenge", + "reward", + "rhythm", + "ribcage", + "ringbolt", + "robust", + "rocker", + "ruffled", + "sailboat", + "sawdust", + "scallion", + "scenic", + "scorecard", + "scotland", + "seabird", + "select", + "sentence", + "shadow", + "shamrock", + "showgirl", + "skullcap", + "skydive", + "slingshot", + "slowdown", + "snapline", + "snapshot", + "snowcap", + "snowslide", + "solo", + "southward", + "soybean", + "spaniel", + "spearhead", + "spellbind", + "spheroid", + "spigot", + "spindle", + "spyglass", + "stagehand", + "stagnate", + "stairway", + "standard", + "stapler", + "steamship", + "sterling", + "stockman", + "stopwatch", + "stormy", + "sugar", + "surmount", + "suspense", + "sweatband", + "swelter", + "tactics", + "talon", + "tapeworm", + "tempest", + "tiger", + "tissue", + "tonic", + "topmost", + "tracker", + "transit", + "trauma", + "treadmill", + "trojan", + "trouble", + "tumor", + "tunnel", + "tycoon", + "uncut", + "unearth", + "unwind", + "uproot", + "upset", + "upshot", + "vapor", + "village", + "virus", + "vulcan", + "waffle", + "wallet", + "watchword", + "wayside", + "willow", + "woodlark", + "zulu", +) + +#: Index is the byte value; the word for an odd position. +ODD_WORDS = ( + "adroitness", + "adviser", + "aftermath", + "aggregate", + "alkali", + "almighty", + "amulet", + "amusement", + "antenna", + "applicant", + "apollo", + "armistice", + "article", + "asteroid", + "atlantic", + "atmosphere", + "autopsy", + "babylon", + "backwater", + "barbecue", + "belowground", + "bifocals", + "bodyguard", + "bookseller", + "borderline", + "bottomless", + "bradbury", + "bravado", + "brazilian", + "breakaway", + "burlington", + "businessman", + "butterfat", + "camelot", + "candidate", + "cannonball", + "capricorn", + "caravan", + "caretaker", + "celebrate", + "cellulose", + "certify", + "chambermaid", + "cherokee", + "chicago", + "clergyman", + "coherence", + "combustion", + "commando", + "company", + "component", + "concurrent", + "confidence", + "conformist", + "congregate", + "consensus", + "consulting", + "corporate", + "corrosion", + "councilman", + "crossover", + "crucifix", + "cumbersome", + "customer", + "dakota", + "decadence", + "december", + "decimal", + "designing", + "detector", + "detergent", + "determine", + "dictator", + "dinosaur", + "direction", + "disable", + "disbelief", + "disruptive", + "distortion", + "document", + "embezzle", + "enchanting", + "enrollment", + "enterprise", + "equation", + "equipment", + "escapade", + "eskimo", + "everyday", + "examine", + "existence", + "exodus", + "fascinate", + "filament", + "finicky", + "forever", + "fortitude", + "frequency", + "gadgetry", + "galveston", + "getaway", + "glossary", + "gossamer", + "graduate", + "gravity", + "guitarist", + "hamburger", + "hamilton", + "handiwork", + "hazardous", + "headwaters", + "hemisphere", + "hesitate", + "hideaway", + "holiness", + "hurricane", + "hydraulic", + "impartial", + "impetus", + "inception", + "indigo", + "inertia", + "infancy", + "inferno", + "informant", + "insincere", + "insurgent", + "integrate", + "intention", + "inventive", + "istanbul", + "jamaica", + "jupiter", + "leprosy", + "letterhead", + "liberty", + "maritime", + "matchmaker", + "maverick", + "medusa", + "megaton", + "microscope", + "microwave", + "midsummer", + "millionaire", + "miracle", + "misnomer", + "molasses", + "molecule", + "montana", + "monument", + "mosquito", + "narrative", + "nebula", + "newsletter", + "norwegian", + "october", + "ohio", + "onlooker", + "opulent", + "orlando", + "outfielder", + "pacific", + "pandemic", + "pandora", + "paperweight", + "paragon", + "paragraph", + "paramount", + "passenger", + "pedigree", + "pegasus", + "penetrate", + "perceptive", + "performance", + "pharmacy", + "phonetic", + "photograph", + "pioneer", + "pocketful", + "politeness", + "positive", + "potato", + "processor", + "provincial", + "proximate", + "puberty", + "publisher", + "pyramid", + "quantity", + "racketeer", + "rebellion", + "recipe", + "recover", + "repellent", + "replica", + "reproduce", + "resistor", + "responsive", + "retraction", + "retrieval", + "retrospect", + "revenue", + "revival", + "revolver", + "sandalwood", + "sardonic", + "saturday", + "savagery", + "scavenger", + "sensation", + "sociable", + "souvenir", + "specialist", + "speculate", + "stethoscope", + "stupendous", + "supportive", + "surrender", + "suspicious", + "sympathy", + "tambourine", + "telephone", + "therapist", + "tobacco", + "tolerance", + "tomorrow", + "torpedo", + "tradition", + "travesty", + "trombonist", + "truncated", + "typewriter", + "ultimate", + "undaunted", + "underfoot", + "unicorn", + "unify", + "universe", + "unravel", + "upcoming", + "vacancy", + "vagabond", + "vertigo", + "virginia", + "visitor", + "vocalist", + "voyager", + "warranty", + "waterloo", + "whimsical", + "wichita", + "wilmington", + "wyoming", + "yesteryear", + "yucatan", +) + +#: word -> (byte value, parity), for reading a code back. Parity 0 is the even list, 1 the odd list. +LOOKUP = {w: (i, 0) for i, w in enumerate(EVEN_WORDS)} +LOOKUP.update({w: (i, 1) for i, w in enumerate(ODD_WORDS)})