From a6d2be15ea5cee07e196ab3cda3e392fc4abc84b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 05:24:33 +0530 Subject: [PATCH 01/81] chore(bindings): spike a ble-to-wi-fi fast link between android and ios throwaway phase 1 hooks, not a design. android hosts a wi-fi direct group with given credentials (or a localonlyhotspot) on an adb broadcast, and can stop its lan carrier so a pair on one network meets only over ble. ios joins with nehotspotconfiguration from a config file in its container and dials the host's existing peer-stream listener directly. no udl or js surface. --- .../java/com/offlineprotocol/FastLinkSpike.kt | 198 ++++++++++++++++++ .../com/offlineprotocol/WifiDirectManager.kt | 15 ++ .../react-native/ios/WifiDirectManager.swift | 117 +++++++++++ 3 files changed, 330 insertions(+) create mode 100644 bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt new file mode 100644 index 000000000..bb7b1b1fc --- /dev/null +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt @@ -0,0 +1,198 @@ +package com.offlineprotocol + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.ConnectivityManager +import android.net.wifi.WifiManager +import android.net.wifi.p2p.WifiP2pConfig +import android.net.wifi.p2p.WifiP2pManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import java.net.Inet4Address +import java.net.NetworkInterface + +/** + * SPIKE (BLE-to-Wi-Fi fast link, phase 1). Throwaway: not a design. + * + * Driven from adb so the spike needs no UDL or JS surface: + * + * adb shell am broadcast -a com.offlineprotocol.SPIKE_FAST_LINK \ + * --es op host --es ssid DIRECT-sp-fastlink --es pass [--ei band 2|5] + * ... --es op lohs (LocalOnlyHotspot; the system picks the credentials) + * ... --es op info (group, Wi-Fi and interface state) + * ... --es op stop (remove the group, close the hotspot) + * ... --es op nolan (stop the LAN carrier: no shared network) + * + * Everything it learns goes to logcat under [TAG]. The peer stream itself is + * the manager's: its listener binds every interface on the group port, so an + * iPhone that joins the group or the hotspot dials it like any other. + */ +internal class FastLinkSpike( + private val context: Context, + /** Stops the LAN carrier, so a pair on one Wi-Fi network meets only over BLE. */ + private val stopLan: () -> Unit = {}, +) { + companion object { + const val TAG = "OPSPIKE" + const val ACTION = "com.offlineprotocol.SPIKE_FAST_LINK" + } + + private val handler = Handler(Looper.getMainLooper()) + private val p2p = context.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager + private val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + private var channel: WifiP2pManager.Channel? = null + private var reservation: WifiManager.LocalOnlyHotspotReservation? = null + private var t0 = 0L + + private val receiver = object : BroadcastReceiver() { + override fun onReceive(c: Context, intent: Intent) { + val op = intent.getStringExtra("op") ?: "info" + log("op=$op") + when (op) { + "host" -> host( + intent.getStringExtra("ssid") ?: "DIRECT-sp-fastlink", + intent.getStringExtra("pass") ?: "", + intent.getIntExtra("band", 0), + ) + "lohs" -> lohs() + "stop" -> stopAll() + "nolan" -> stopLan() + else -> info() + } + } + } + + fun register() { + val filter = IntentFilter(ACTION) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED) + } else { + context.registerReceiver(receiver, filter) + } + log("registered") + } + + fun unregister() { + try { context.unregisterReceiver(receiver) } catch (_: Exception) {} + stopAll() + channel?.close() + channel = null + } + + private fun log(message: String) { + val since = if (t0 == 0L) 0 else SystemClock.elapsedRealtime() - t0 + Log.i(TAG, "wall=${System.currentTimeMillis()} +${since}ms $message") + } + + private fun ch(): WifiP2pManager.Channel? { + if (channel == null) channel = p2p?.initialize(context, Looper.getMainLooper(), null) + return channel + } + + @SuppressLint("MissingPermission") + private fun host(ssid: String, pass: String, band: Int) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { log("host needs API 29"); return } + val p2p = p2p ?: run { log("no p2p"); return } + val ch = ch() ?: run { log("no channel"); return } + t0 = SystemClock.elapsedRealtime() + val builder = WifiP2pConfig.Builder() + .setNetworkName(ssid) + .setPassphrase(pass) + .enablePersistentMode(false) + when (band) { + 2 -> builder.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_2GHZ) + 5 -> builder.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_5GHZ) + } + val config = builder.build() + // Whatever group exists goes first: createGroup fails BUSY beside one. + p2p.removeGroup(ch, object : WifiP2pManager.ActionListener { + override fun onSuccess() = create() + override fun onFailure(reason: Int) = create() + fun create() { + log("createGroup ssid=$ssid band=$band") + p2p.createGroup(ch, config, object : WifiP2pManager.ActionListener { + override fun onSuccess() { + log("createGroup ok") + handler.postDelayed({ info() }, 1500) + handler.postDelayed({ info() }, 5000) + } + override fun onFailure(reason: Int) = log("createGroup failed reason=$reason") + }) + } + }) + } + + @SuppressLint("MissingPermission") + private fun lohs() { + val wifi = wifi ?: run { log("no wifi"); return } + t0 = SystemClock.elapsedRealtime() + try { + wifi.startLocalOnlyHotspot(object : WifiManager.LocalOnlyHotspotCallback() { + override fun onStarted(r: WifiManager.LocalOnlyHotspotReservation) { + reservation = r + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val c = r.softApConfiguration + log("lohs started ssid=${c.ssid} pass=${c.passphrase} security=${c.securityType}") + } else { + @Suppress("DEPRECATION") + val c = r.wifiConfiguration + log("lohs started ssid=${c?.SSID} pass=${c?.preSharedKey}") + } + handler.postDelayed({ info() }, 1500) + } + override fun onStopped() = log("lohs stopped") + override fun onFailed(reason: Int) = log("lohs failed reason=$reason") + }, handler) + } catch (e: Exception) { + log("lohs threw ${e.javaClass.simpleName}: ${e.message}") + } + } + + @SuppressLint("MissingPermission") + private fun stopAll() { + reservation?.close() + reservation = null + val ch = channel ?: return + p2p?.removeGroup(ch, object : WifiP2pManager.ActionListener { + override fun onSuccess() = log("group removed") + override fun onFailure(reason: Int) = log("remove group failed reason=$reason") + }) + } + + @SuppressLint("MissingPermission") + private fun info() { + val ch = ch() + if (ch != null) { + p2p?.requestGroupInfo(ch) { g -> + if (g == null) { + log("group none") + } else { + val freq = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) g.frequency else -1 + log("group name=${g.networkName} pass=${g.passphrase} owner=${g.isGroupOwner} " + + "iface=${g.`interface`} freq=$freq clients=${g.clientList.size}") + } + } + } + @Suppress("DEPRECATION") + val ci = wifi?.connectionInfo + @Suppress("DEPRECATION") + log("wifi enabled=${wifi?.isWifiEnabled} sta ssid=${ci?.ssid} freq=${ci?.frequency} rssi=${ci?.rssi}") + val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager + log("default network=${cm?.activeNetwork}") + try { + for (nif in NetworkInterface.getNetworkInterfaces()) { + if (!nif.isUp) continue + val v4 = nif.inetAddresses.toList().filterIsInstance() + if (v4.isNotEmpty()) log("iface ${nif.name} ${v4.joinToString { it.hostAddress ?: "?" }}") + } + } catch (e: Exception) { + log("interfaces: ${e.message}") + } + } +} diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index aaaa86c8b..f9bfb930d 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -187,6 +187,8 @@ class WifiDirectManager( // Whether the listener holds the port a group's clients dial. Written at // start, read by formation on the transport thread. private var ownsGroupPort = false + // SPIKE(fast-link) + private var spike: FastLinkSpike? = null // Every socket from its first byte to its end: the preamble, the framing, // one announced stream per address, the writers. This manager owns the @@ -513,6 +515,16 @@ class WifiDirectManager( // Start server socket on the port bound above. startServerSocket(listener) + // SPIKE(fast-link): adb-driven group and hotspot hosting. + spike = FastLinkSpike(context) { + transportHandler.post { + lan?.stop() + lan = null + sockets.closeCarrier(PeerStreamSockets.Carrier.LAN) + Log.i(FastLinkSpike.TAG, "LAN carrier stopped") + } + }.also { it.register() } + updateState(TransportState.RUNNING) // Notify protocol. Wi-Fi P2P off at start arrives next as the @@ -595,6 +607,9 @@ class WifiDirectManager( // Stop server socket stopServerSocket() + spike?.unregister() + spike = null + lan?.stop() lan = null diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index baa93afb0..7b5dce8c1 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -10,6 +10,11 @@ import Foundation import Network +import os.log +// SPIKE(fast-link): scoped, because the module also exports a legacy NWEndpoint. +import class NetworkExtension.NEHotspotConfiguration +import class NetworkExtension.NEHotspotConfigurationManager +import class NetworkExtension.NEHotspotNetwork /// The engine's peer-stream slot on iOS, over `NWListener`, `NWBrowser` and /// `NWConnection`. @@ -285,6 +290,7 @@ public class WifiDirectManager: NSObject, TransportManager { updateState(.running) try? protocolInstance.wifiDirectStatusChanged(isConnected: true) emitDiagnostic("info", "Peer-stream transport started") + spikeJoinIfConfigured() } public func stop() { @@ -793,6 +799,7 @@ extension WifiDirectManager: PeerStreamHost { "error": error.localizedDescription ]) } + spikeLog("peer stream proved \(address)") } func peerStreamReceived(_ address: String, _ body: Data) { @@ -825,3 +832,113 @@ extension WifiDirectManager: PeerStreamHost { } extension WifiDirectManager: @unchecked Sendable {} + +// MARK: - SPIKE (BLE-to-Wi-Fi fast link, phase 1). Throwaway: not a design. +// +// Driven from the Mac, so the spike needs no UDL or JS surface. Copy a JSON +// file into the app's container: +// +// {"ssid":"DIRECT-sp-...","pass":"","host":"192.168.49.1"} +// xcrun devicectl device copy to --device \ +// --domain-type appDataContainer --domain-identifier \ +// --source opspike.json --destination Documents/opspike.json +// +// Optional keys: port (default 8988), joinOnce (default true), addr (the +// address the preamble must prove). Launch arguments (-opSpikeSSID and so on) +// work too, but iOS relaunches the app for Bluetooth restoration without them. +// The join runs when this transport starts. Logs go to os_log as "OPSPIKE". +extension WifiDirectManager { + private static var spikeT0: TimeInterval = 0 + private static let spikeOSLog = OSLog(subsystem: "com.offlineprotocol.spike", category: "OPSPIKE") + + func spikeLog(_ message: String) { + let now = ProcessInfo.processInfo.systemUptime + let since = Self.spikeT0 == 0 ? 0 : Int((now - Self.spikeT0) * 1000) + let line = "OPSPIKE wall=\(Int64(Date().timeIntervalSince1970 * 1000)) +\(since)ms \(message)" + os_log("%{public}@", log: Self.spikeOSLog, type: .default, line) + } + + fileprivate func spikeJoinIfConfigured() { + // Documents/opspike.json, copied in with `devicectl device copy to`, + // wins over launch arguments: iOS relaunches the app for Bluetooth + // restoration, and a relaunch carries no arguments. + var config: [String: Any] = [:] + if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first, + let data = try? Data(contentsOf: dir.appendingPathComponent("opspike.json")), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + config = object + } else { + let defaults = UserDefaults.standard + for key in ["ssid": "opSpikeSSID", "pass": "opSpikePass", "host": "opSpikeHost", "addr": "opSpikeAddr"] { + if let value = defaults.string(forKey: key.value) { config[key.key] = value } + } + if defaults.integer(forKey: "opSpikePort") != 0 { config["port"] = defaults.integer(forKey: "opSpikePort") } + if defaults.object(forKey: "opSpikeJoinOnce") != nil { config["joinOnce"] = defaults.bool(forKey: "opSpikeJoinOnce") } + } + spikeLog("transport started; spike config ssid=\(config["ssid"] as? String ?? "nil")") + guard let ssid = config["ssid"] as? String, + let pass = config["pass"] as? String, + let host = config["host"] as? String else { return } + let port = config["port"] as? Int ?? 0 + let joinOnce = config["joinOnce"] as? Bool ?? true + let expected = config["addr"] as? String + Self.spikeT0 = ProcessInfo.processInfo.systemUptime + spikeLog("apply ssid=\(ssid) joinOnce=\(joinOnce) host=\(host):\(port == 0 ? 8988 : port)") + let configuration = NEHotspotConfiguration(ssid: ssid, passphrase: pass, isWEP: false) + configuration.joinOnce = joinOnce + NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] error in + guard let self = self else { return } + if let error = error as NSError? { + self.spikeLog("apply finished error domain=\(error.domain) code=\(error.code) \(error.localizedDescription)") + // alreadyAssociated (13) is a join that already holds. + if error.code != 13 { return } + } else { + self.spikeLog("apply finished ok") + } + NEHotspotNetwork.fetchCurrent { network in + self.spikeLog("current network ssid=\(network?.ssid ?? "nil") bssid=\(network?.bssid ?? "nil")") + } + self.spikeDial(host: host, port: port == 0 ? 8988 : port, expected: expected, attempt: 1) + } + } + + /// Dials the host's listener directly: there is no DNS-SD on the group. + /// Retried each second until a stream proves its peer, for 30 attempts. + private func spikeDial(host: String, port: Int, expected: String?, attempt: Int) { + linkQueue.async { [weak self] in + guard let self = self, self.state == .running else { return } + if !self.peers.isEmpty, let expected = expected, self.peers.handle(for: expected) != nil { + self.spikeLog("already proved \(expected); not dialing") + return + } + self.spikeLog("dial attempt \(attempt) to \(host):\(port)") + let endpoint = NWEndpoint.hostPort( + host: NWEndpoint.Host(host), port: NWEndpoint.Port(integerLiteral: UInt16(port))) + let parameters = Self.makeParameters() + parameters.requiredInterfaceType = .wifi + let stream = Stream( + connection: NWConnection(to: endpoint, using: parameters), + outbound: true, + dialed: nil + ) + self.peers.claim(expected, for: stream) + self.open(stream) + // Wrapped after open(): both run on linkQueue, so no state change + // is delivered in between. + let handler = stream.connection.stateUpdateHandler + stream.connection.stateUpdateHandler = { [weak self, weak stream] state in + let local = stream?.connection.currentPath?.localEndpoint + self?.spikeLog("dial \(attempt) state \(state) local=\(String(describing: local))") + handler?(state) + } + self.linkQueue.asyncAfter(deadline: .now() + 3) { [weak self] in + guard let self = self else { return } + if self.peers.provedAddress(of: stream) != nil { return } + if attempt >= 30 { self.spikeLog("giving up"); return } + if case .ready = stream.connection.state { return } + stream.connection.cancel() + self.spikeDial(host: host, port: port, expected: expected, attempt: attempt + 1) + } + } + } +} From 1447c1b9cd5c610cba5475c43cf5f0f976509cee Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 05:37:08 +0530 Subject: [PATCH 02/81] docs: decide and specify the ble-to-wi-fi fast link adr 0038 records the decision from the phase 1 spike: two devices that share a confirmed session but meet only over bluetooth le bring up a wi-fi direct network on request, with fresh credentials sealed in the session, and the stream over it fills the peer-stream slot. the fast link state machine specifies roles, frames, timers and teardown. threat model r34 records what the network exposes in range and what the offer trusts. --- CLAUDE.md | 1 + docs/README.md | 5 +- .../0028-android-peer-streams-join-the-lan.md | 3 +- ...fast-link-is-offered-inside-the-session.md | 153 ++++++++++++++++++ docs/adr/README.md | 1 + docs/security/threat-model.md | 46 ++++++ docs/spec/stream-framing.md | 8 + docs/state-machines/README.md | 10 +- docs/state-machines/fast-link.md | 133 +++++++++++++++ docs/state-machines/service-subscriptions.md | 2 +- 10 files changed, 356 insertions(+), 6 deletions(-) create mode 100644 docs/adr/0038-a-fast-link-is-offered-inside-the-session.md create mode 100644 docs/state-machines/fast-link.md diff --git a/CLAUDE.md b/CLAUDE.md index 7a44e12ab..4eb6c7a4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,6 +24,7 @@ that are versioned, reviewable, and readable by people who are not an agent. | `offline-protocol-core`: adding an import, a dependency, or a constructor | ADR [0020](docs/adr/0020-core-compiles-without-std.md) (it is dual std/no_std) | | `offline-protocol-sealed`: the envelope codec, `derive_address`, canonical signing payloads, ratchet constants, the 1:1 control-frame prefixes, `KeyPackagePayload`, the identity assertion codec | ADR [0022](docs/adr/0022-one-sealed-layer-shared-with-the-leaf.md) (also dual std/no_std, and the one home for each) | | `offline-protocol-leaf`: anything a device does at pairing, on a frame, or with its store | ADR [0021](docs/adr/0021-a-leaf-node-speaks-mls.md) and [docs/spec/leaf-provisioning.md](docs/spec/leaf-provisioning.md) (a time source, real entropy, durable-before-emit and authorization are obligations, not suggestions) | +| The fast link: bringing up Wi-Fi between two devices that meet over Bluetooth, the `__FAST_LINK__` frame, the bridges' host and join code | ADR [0038](docs/adr/0038-a-fast-link-is-offered-inside-the-session.md) and [the fast link state machine](docs/state-machines/fast-link.md) (credentials only ever travel sealed and ephemeral; the host admits only the invitee) | | Replicated documents: the store, sync frames, attachments | [docs/spec/data-sync.md](docs/spec/data-sync.md), [the replication state machine](docs/state-machines/data-replication.md), ADR [0018](docs/adr/0018-data-layer-engine-and-storage-seams.md) and [0019](docs/adr/0019-remote-document-imports-are-contained-not-trusted.md) | | Any binding: Swift, Kotlin, Python, TypeScript, C, Java, Ruby, the browser | [docs/bridges/](docs/bridges/README.md) | | The C API: `offline-protocol-uniffi/src/capi`, `bindings/c` | [docs/bridges/c.md](docs/bridges/c.md) (the dispatcher is generated from the UDL; the header is generated by cbindgen and committed) | diff --git a/docs/README.md b/docs/README.md index cde8ac682..f8d9ca5e1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -88,7 +88,7 @@ implementation written against these documents should interoperate. | Document | Governs | |----------|---------| -| [Overview](state-machines/README.md) | The invariant that spans all seven | +| [Overview](state-machines/README.md) | The invariant that spans all eight | | [Delivery and acknowledgements](state-machines/delivery-and-acks.md) | What happens to an inbound frame, and when a receiver acknowledges | | [Outbox and retries](state-machines/outbox-and-retries.md) | An outbound message from send to terminal state | | [Session lifecycle](state-machines/session-lifecycle.md) | 1:1 MLS establishment, confirmation, desync, and heal | @@ -96,12 +96,13 @@ implementation written against these documents should interoperate. | [Transport lifecycle](state-machines/transport-lifecycle.md) | Transport availability, scoring, switching, escalation | | [Document replication](state-machines/data-replication.md) | A document from edit to durable record, a space from offer to convergence, an attachment fetch | | [Service subscriptions](state-machines/service-subscriptions.md) | A subscription from subscribe to end on both sides, and an update from publish to delivery | +| [Fast link](state-machines/fast-link.md) | A Wi-Fi link two devices bring up through their session, from request to close | ## Decisions | Document | Scope | |----------|-------| -| [ADR index](adr/README.md) | Thirty-seven decisions that are expensive to reverse or easy to undo by accident | +| [ADR index](adr/README.md) | Thirty-eight decisions that are expensive to reverse or easy to undo by accident | If something in the codebase looks redundant or over-engineered, check here before simplifying it. diff --git a/docs/adr/0028-android-peer-streams-join-the-lan.md b/docs/adr/0028-android-peer-streams-join-the-lan.md index 05a43b7a6..b1929bb9a 100644 --- a/docs/adr/0028-android-peer-streams-join-the-lan.md +++ b/docs/adr/0028-android-peer-streams-join-the-lan.md @@ -52,7 +52,8 @@ the other closes, and the pair reconnects forever with no error on either side. - An Android phone reaches an iPhone or a Python host on the same Wi-Fi network. With no shared network they still do not meet; that needs Wi-Fi - Aware on both. + Aware on both. (Since [ADR 0038](0038-a-fast-link-is-offered-inside-the-session.md), + two that share a session can bring up a network for it on request.) - A group client that is the higher address can no longer supersede its own half-open stream. Its reconnect is refused until keepalive ends the stale one, about thirty seconds, where "newer supersedes" reconnected at once. diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md new file mode 100644 index 000000000..faf943c28 --- /dev/null +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -0,0 +1,153 @@ +# 0038. Two devices that meet over Bluetooth bring up Wi-Fi through their session + +**Status:** Accepted + +## Context + +An iPhone and an Android phone with no shared network meet only over +Bluetooth LE ([ADR 0028](0028-android-peer-streams-join-the-lan.md): "With no +shared network they still do not meet"). Every attachment between them is +capped by Bluetooth: a 1 MiB file took 197.7 s on the lab pair, about +5.3 KB/s, and an envelope over about 71 KB does not fit at all. + +The engine already has a slot for a faster link, the peer stream +([stream framing](../spec/stream-framing.md)). Once a stream's preamble proves +the peer's address, everything above the slot works: the transport selector +weights the slot by bandwidth, a file transfer pins to it once a stream proves +the recipient, and outboxes and acknowledgements make falling back to +Bluetooth lossless. What two phones without a shared network lack is a network +to open the stream over. + +Neither platform lets an application make one silently, but each lets it make +one with credentials: + +- Android 10 and later creates a Wi-Fi Direct group with a chosen network name + and passphrase (`WifiP2pConfig.Builder`), and its owner is an ordinary WPA2 + access point to a device that does not speak Wi-Fi Direct. The SDK already + forms groups this way, with credentials derived from the application id + ([R22](../security/threat-model.md#r22-an-android-wi-fi-direct-group-admits-anyone-who-knows-the-application-id)). +- iOS joins a network by name and passphrase with `NEHotspotConfiguration`, + after a system prompt. It cannot host one. + +A spike on a Samsung SM-M176B and an iPhone 16 (November 2026) settled the +open question: the iPhone joined the Samsung's group from credentials it was +handed, dialed the Samsung's existing listener and the preamble verified in +both directions. Join tap to verified preamble took 11.3 to 13.6 s, about +10 s of it inside iOS between its scan and its association. The 1 MiB file took +8.0 to 8.7 s. The Samsung stayed on its own Wi-Fi throughout. The iPhone +showed "“App” Wants to Join Wi‑Fi Network “NAME”?" on every join, left its own +Wi-Fi for the group, and, with `joinOnce`, disconnected 15 s after the app left +the foreground and deleted the passphrase. + +## Decision + +1. **A fast link is a Wi-Fi network one device hosts for one peer, whose + credentials travel inside their confirmed 1:1 MLS session.** The stream + opened over it is an ordinary peer stream: the same preamble, the same + framing, the same slot. The engine above the slot learns nothing new about + it. + +2. **It is brought up on demand, never on discovery.** The application calls + `request_fast_link(peer)`, and `close_fast_link(peer)` ends it early. There + is no automatic trigger. Every join on iOS puts a system prompt in front of + the user and takes the phone off the user's own network, so whether that is + worth it for a given transfer is the application's call, not the engine's. + +3. **The platform says what it can do, and the engine assigns the roles.** A + platform declares `can_host` and `can_join` once it knows its permissions: + Android 10 and later both, iOS join only, everything else neither. A + requester that can host hosts; one that can only join asks its peer to + host. When both ask at once, the lower address (compared by UTF-8 bytes, as + for streams) hosts and the other side joins. + +4. **The engine makes the credentials, fresh for every link.** The network + name is `DIRECT-`, two random characters, `-` and twelve random hex digits: + Android requires the prefix, and nothing in the name derives from the + application, the user or the device ([ADR 0037](0037-an-applications-users-are-visible-only-to-that-application.md)). + The passphrase is 32 random hex digits, 128 bits. The host's platform + brings the network up with exactly these and reports the address and port + its listener holds. + +5. **Three frames, under one new prefix, `__FAST_LINK__`, which only ever + travels inside a decrypted 1:1 MLS plaintext**, like `__DATA_V1__`: + `request`, `offer` and `close`. Each is sealed with the strict encryptor (a + confirmed session or nothing) and sent once over the live direct link with + no acknowledgement, outbox or retry ([ADR 0032](0032-ephemeral-sends-go-once-over-a-live-link.md)). + An offer delivered late is worse than one lost: the network it names is + gone, and the joiner would prompt its user for nothing. A frame is sent + only to a peer whose key package advertised `link_versions` entry 1. + MLS authenticates the sender, hides the passphrase, and refuses a replayed + ciphertext; the offer's own lifetime bounds a slow delivery. + +6. **The stream proves it reached the right peer, and the host admits only + the invitee.** The joiner dials the offered address and port with the + host's address as its claim, so a different preamble closes the stream + (step four of the preamble). The host refuses, on the network it made, any + proved address other than the one it invited. The offered address must be + a private or link-local IP literal: never a name to resolve, never a route + off the network just joined. + +7. **The engine ends a link** when its offer expires unused (120 s), when the + proved stream is lost, after 60 s with nothing carried and no transfer to + the peer under way, on either side's `close`, and on the application's + `close_fast_link`. A joiner's platform reports its own end when it can no + longer hold the network: iOS does when the application leaves the + foreground, because iOS disconnects 15 s later anyway and the host would + otherwise hold a dead stream until keepalive notices, measured at 40 s. + Bluetooth stays up throughout and carries the traffic before, during the + switch and after. + +8. **One link at a time per device.** A phone joins one Wi-Fi network at a + time and an Android device owns at most one Wi-Fi Direct group, so a second + request is refused as busy rather than queued. + +9. **The media window on the peer-stream slot is 16 chunks, not 4.** With + 32 KiB chunks and a window of 4 the transfer waited on acknowledgements: + about 128 KiB a round, which is what the spike measured (126 KB/s), far + below the link. Every other slot keeps its window. + +### Why not LocalOnlyHotspot as a fallback + +Android's `LocalOnlyHotspot` worked in the spike, but the system picks its +credentials: a passphrase of 15 lowercase letters and digits, about 77 bits, +under the floor of decision 4, which an application cannot raise. It also +needs location on older releases, and on phones without concurrent station +and access point it drops the user's own Wi-Fi. No case was seen where Wi-Fi +Direct failed and it would have helped, so it is left out rather than shipped +untested. + +### Why not derive the credentials, as group formation does + +That is R22: a passphrase anyone with the application id can compute admits +anyone. Formation derives them because two devices that have not heard each +other have no channel to agree on a secret. A fast link always has one, the +session, and only uses it. + +## Consequences + +- An iPhone and an Android phone with no shared network move a file about 20 + times faster than over Bluetooth, after one prompt on the iPhone. A message + too large for Bluetooth fits the slot's 1 MiB ceiling. +- The join takes the iPhone off its own Wi-Fi for as long as the link lasts, + and the link lasts only while the application is in the foreground. An + application should ask for a link when a transfer is worth that, and expect + it to end when the user leaves. +- An iOS application that uses it needs the Hotspot Configuration entitlement + (`com.apple.developer.networking.HotspotConfiguration`) and local-network + permission. An Android application needs `NEARBY_WIFI_DEVICES` on Android 13 + and later, and fine location below it. +- A fast link and Wi-Fi Direct group formation (`wifiDirect.autoAccept`) share + the one group an Android device can own: while either holds it, the other + is refused. +- The network's name and existence are visible to anyone in radio range for + as long as it is up, and its passphrase only to the two devices + ([R34](../security/threat-model.md#r34-a-fast-link-network-is-visible-in-range-and-its-offer-trusts-the-session)). +- The runtime behaviour is the [fast link state machine](../state-machines/fast-link.md). + +## What would undo this + +Wi-Fi Aware on both platforms would let two phones open a stream without +either one hosting a network or prompting, and the slot would not notice the +change. Until a pairing-capable Android phone proves it against an iPhone, +this is the path. Going back to deriving credentials would reopen R22 for a +case that has a secure channel to use. diff --git a/docs/adr/README.md b/docs/adr/README.md index b49079eab..095716a44 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -48,6 +48,7 @@ silently undo it. Decisions that follow from the obvious default do not need one | [0035](0035-a-service-can-be-subscribed-to.md) | A service can be subscribed to: sealed, leased, `latest` or `log`, recoverable | Accepted | | [0036](0036-a-topic-can-be-backed-by-a-group.md) | A topic can be backed by a group: one encryption per publish, revocation by commit | Proposed | | [0037](0037-an-applications-users-are-visible-only-to-that-application.md) | An application's users are visible only to that application | Proposed | +| [0038](0038-a-fast-link-is-offered-inside-the-session.md) | Two devices that meet over Bluetooth bring up Wi-Fi through their session | Accepted | ## Format diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 37c1d3cc1..0665e5f80 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1448,6 +1448,52 @@ signature it cannot otherwise check, on a field whose only effect is bounded this way. Without generations a frame or receipt lost past the first forwarder stayed lost for the whole window, which is the larger cost. +### R34. A fast-link network is visible in range, and its offer trusts the session + +While a fast link is up ([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md)), +its host broadcasts a Wi-Fi Direct group. Anyone in radio range (A1) sees that a +group exists, its name, its channel, and when it comes and goes, and can +correlate it with the Bluetooth LE advertisement of the device beside it. The +name is random and derives from nothing, so it says no more than that a +Wi-Fi Direct group is up. + +**Who can join:** unlike the formation group of +[R22](#r22-an-android-wi-fi-direct-group-admits-anyone-who-knows-the-application-id), +the passphrase is 128 random bits, fresh for each link, and leaves the host +only sealed in its confirmed session with the invitee. A device in range cannot +compute it, and a WPA2 handshake it captures does not give it up to an offline +guess at that length. Wi-Fi Direct also lets a nearby device ask the owner to +admit it by push button or PIN, which Android puts to the owner's user as a +system invitation; a user who accepts one admits that device to the network, +and nothing more. + +**What being on the network gives:** a stream, opened like any other, that must +prove an address with the preamble. The host refuses any proved address but +the invitee's on that network, and a replayed preamble +([R16](#r16-the-identity-assertion-is-static-and-replayable-on-every-carrier)) +labels a stream with the invitee's address that its holder cannot use. + +**What the offer trusts:** the session. The invitee learns the passphrase and +the host's address and can hand them on, and a peer that shares a session can +already send anything. A hostile session peer can offer a network it controls +and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The +offered address must be a private or link-local IP literal, the joiner's dial +is bound to the Wi-Fi interface, and the stream must prove the offerer's own +address, so a link that proves nothing ends when its offer expires, at most +300 s later. While a joiner is on the host's network the host is its access +point, and sees whatever else the joiner's device sends there, as any access +point does: name lookups and connection attempts of other applications, with +no route onward. + +**Availability:** anyone who can drop Bluetooth frames between the two can stop +a link from forming, which is no more than they could already do to the +messages themselves. The traffic stays on Bluetooth. + +**Why it stands:** a network that does not broadcast its existence cannot be +joined by an iPhone that was handed its name, and the session is the only +channel the two devices share. Both sides of the residual are the price of a +link the user asked for and can see. + ## Network egress Until 0.26 the Rust crates opened no socket: every byte that left a device diff --git a/docs/spec/stream-framing.md b/docs/spec/stream-framing.md index 4532e5b35..8037debac 100644 --- a/docs/spec/stream-framing.md +++ b/docs/spec/stream-framing.md @@ -311,6 +311,14 @@ the same exposure as a Bluetooth LE advertisement, and the same answer: the address is public by design, and what it does not reveal (who the human is, who they talk to) is protected above this layer. +Where two devices share no network, one may bring a network up for the other +on request, with its credentials sent inside their session: the fast link +([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md)). Nothing +in this chapter changes over it. There is no discovery record: the joiner +dials the address and port the offer named, with the host's address as its +claim (step four above), and the host admits no other proved address on the +network it made. + ## Position among the transports The engine has one slot for a platform-established peer stream, and it is the diff --git a/docs/state-machines/README.md b/docs/state-machines/README.md index 510a27882..e9d010e9f 100644 --- a/docs/state-machines/README.md +++ b/docs/state-machines/README.md @@ -1,6 +1,6 @@ # State machines -Seven state machines govern the protocol's runtime behaviour. Each is documented +Eight state machines govern the protocol's runtime behaviour. Each is documented with its states, its transitions, the invariants that hold across them, and the failure modes that the current shape exists to prevent. @@ -13,6 +13,7 @@ failure modes that the current shape exists to prevent. | [Transport lifecycle](transport-lifecycle.md) | Transport availability, scoring, switching, and escalation | | [Document replication](data-replication.md) | A document from edit to durable record, a space from offer to convergence, an attachment fetch to one of six ends | | [Service subscriptions](service-subscriptions.md) | A subscription from subscribe to end on both sides, and an update from publish to delivery | +| [Fast link](fast-link.md) | A Wi-Fi link two devices bring up through their session, from request to close | ## How to read these @@ -24,7 +25,7 @@ Several of these shapes look over-engineered until you know which bug they close and the surrounding prose is there so a future change does not undo one by accident. -## The one invariant that spans all seven +## The one invariant that spans all eight **Custody of an undelivered message stays with the sender until a receiver positively confirms it.** @@ -49,3 +50,8 @@ and the newer value takes custody in its place is never written to the outbox's store, so a restart, after which the stream or `sub_id` it names no longer exists, discards it. Neither gives up a value the receiver still needs. + +A fast link holds no message at all. Its own frames are ephemeral and are lost +rather than delivered late ([ADR 0032](../adr/0032-ephemeral-sends-go-once-over-a-live-link.md)), +and what it carries is ordinary traffic on the ordinary ladder, which falls +back to Bluetooth LE when the link ends. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md new file mode 100644 index 000000000..a29615e02 --- /dev/null +++ b/docs/state-machines/fast-link.md @@ -0,0 +1,133 @@ +# Fast link + +Two devices that share a confirmed session but meet only over Bluetooth LE +bring up a Wi-Fi network between them, and a peer stream over it fills the +`wifi_direct` slot. The decision and its reasons are +[ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md); the frame +is in [control messages](../spec/control-messages.md#fast-link-frames). This +document is the runtime behaviour: what each side holds, what moves it, and +what each shape prevents. + +## Invariants + +1. **Credentials leave a device only inside the confirmed 1:1 session with the + peer they are for.** A fast-link frame is sealed or not sent, travels once + over a live direct link, and never enters the outbox, a relay or a + neighbour's custody. A frame that arrives in plaintext is never routed here. +2. **A link never announces a peer.** Only a stream's preamble does, exactly as + on every other network. The joiner's stream is opened with the host's + address as its claim, and the host refuses any other proved address on the + network it made. +3. **One link per device at a time.** A second request, from either side, is + answered `busy`. +4. **Whichever side ends a link tells its own platform and the peer.** A lost + `close` is bounded by the other side's own timers: the offer's lifetime, the + stream's loss, or the idle limit. +5. **No event, diagnostic or telemetry record carries the passphrase.** It + exists in the sealed frame, in the directive handed to the platform, and in + the platform's network configuration, and nowhere else. + +Invariant 1 is why the frames are ephemeral rather than reliable. A reliable +offer that reached the joiner from the outbox after a reconnect would name a +network that no longer exists, and the joiner would prompt its user to join +nothing. + +## Who does what + +The **engine** holds the link, assigns roles, makes credentials, seals and +reads the frames, runs every timer and decides when the link ends. The +**platform** brings a network up or down and opens the stream when the engine +tells it to, and reports what happened. They talk through a queue of +directives the platform drains when its transport callback fires, the same +wake-up that drains outbound stream bodies: + +| Directive | The platform | Then reports | +|-----------|--------------|--------------| +| `host` | Brings up a network with the given name and passphrase, admitting the given peer only | `wifi_direct_fast_link_hosting(link, host, port)`, or `wifi_direct_fast_link_ended(link, reason)` | +| `join` | Joins the given network and dials `host:port`, claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | +| `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | + +A platform declares what it can do with +`wifi_direct_set_fast_link_roles(can_host, can_join)`. Until it does, both are +false and every request is refused. + +## The host + +| State | Entered when | Leaves to | +|-------|--------------|-----------| +| `hosting` | The application asked and this device can host, or a peer's `request` arrived and it can | `offered` on the platform's report; `closed` (`host_failed`) after 20 s without one, or on the platform's `ended` | +| `offered` | The platform reported the network up; the `offer` is sent | `up` when a stream proves the peer; `closed` (`expired`) 120 s after the offer was made | +| `up` | A stream proved the peer while the link was `offered` | `closed` on the stream's loss (`lost`), after 60 s idle (`idle`), on `close` from either side | + +## The joiner + +| State | Entered when | Leaves to | +|-------|--------------|-----------| +| `requested` | The application asked and this device can only join; the `request` is sent | `joining` on the peer's `offer`; `closed` (`no_offer`) after 30 s, or on the peer's `close` | +| `joining` | An `offer` arrived, by request or not, and this device can join | `up` when a stream proves the host; `closed` (`expired`) at the offer's lifetime, measured from its arrival, or on the platform's `ended` | +| `up` | A stream proved the host while the link was `joining` | as for the host | + +## Frames that cross a link + +**A `request` arrives.** A device that cannot host answers `close` +(`cannot_host`); one holding a link with another peer answers `close` (`busy`). +One that already offered this peer a link sends the same offer again, since +the request means the first one was lost. Otherwise it starts hosting under +the request's link id. + +**An `offer` arrives.** A device that cannot join answers `close` +(`cannot_join`), and one holding a link with another peer answers `busy`. An +offer that fails validation (below) is answered `close` (`invalid`) and nothing +else happens. When both devices are hosting for each other, the lower address +keeps hosting: the higher one closes its own link and joins, and the lower one +ignores the higher one's offer, which its owner is about to withdraw. + +**A `close` arrives.** It ends the link with that id, if there is one, and is +never answered. + +An offer is valid when its name is 1 to 32 bytes, its passphrase 8 to 63 +printable ASCII characters, its host a private or link-local IP literal, its +port not zero, its lifetime at most 300 s, and the time it states it was made no +more than 300 s in the future or more than its lifetime plus 300 s in the +past by the receiver's clock. The second bound is generous because two phones' +clocks disagree; what the receiver enforces is its own deadline, the offer's +lifetime from the moment it arrived. + +## Ending a link + +Every end, whatever its cause, does the same three things: a `close` directive +for this device's platform when the platform holds anything for the link, a +`close` frame for the peer when the peer knows of the link and the end did not +come from the peer, and one `fast_link_changed` event with state `closed` and +the reason. + +The idle limit counts a body carried by the slot in either direction for this +peer as activity, and does not run while a file transfer to the peer is in +flight. A link that carries nothing for 60 s is costing the user their own +Wi-Fi for no reason. + +A joiner's platform that is about to lose the network reports it as `ended` +first: on iOS, leaving the foreground, after which iOS disconnects at 15 s +whatever the engine thinks. Without the report the host learns from TCP +keepalive, about 40 s later. + +## Events + +`fast_link_changed` carries the peer, the link id, the role (`host` or +`join`), the state (one of the six above) and, on `closed`, the reason. It is +how the application learns the outcome of `request_fast_link`, which returns +as soon as the first step is taken. It never carries a network name or a +passphrase. + +## What the shapes prevent + +- **An offer through the outbox** reaches the joiner after the network is gone + and prompts its user for nothing. Hence ephemeral frames and a lifetime. +- **A host that admits whoever proves an address** on its network is an access + point for anyone who learns the passphrase, which is what R22 is for group + formation. Hence the admitted peer, and a passphrase only the two hold. +- **Two links at once** are two networks on a phone that can join one, and the + second join drops the first without either side being told. +- **A joiner that falls silent** when iOS takes the network away leaves the + host's stream half open until keepalive ends it. Hence the platform's + report. diff --git a/docs/state-machines/service-subscriptions.md b/docs/state-machines/service-subscriptions.md index 87d2ec98b..0f6f282b2 100644 --- a/docs/state-machines/service-subscriptions.md +++ b/docs/state-machines/service-subscriptions.md @@ -32,7 +32,7 @@ what each shape prevents. Invariant 5 is the one place this state machine gives up custody of an undelivered message before the receiver confirms it, which the -[one invariant that spans all seven](README.md#the-one-invariant-that-spans-all-seven) +[one invariant that spans all eight](README.md#the-one-invariant-that-spans-all-eight) otherwise forbids. It does so only for a value that a newer value for the same key replaces, and the newer value takes custody in its place. From 0f69543eb80088b5b12190f3ba7e7e0e304a254e Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 05:40:32 +0530 Subject: [PATCH 03/81] feat(sealed): reserve the __fast_link__ prefix inside the 1:1 session the literal lives in offline-protocol-sealed with the other pair frames and is reserved in the engine registry and the control-messages chapter, which also specifies the request, offer and close bodies and their bounds. until the handler lands, a fast-link frame is consumed wherever it is found: bare on the wire, in a 1:1 plaintext, and on all three group plaintext arms, so it is never shown to anyone as text. --- .../offline-protocol-sealed/src/prefixes.rs | 20 +++++++-- crates/offline-protocol/src/group_mesh.rs | 18 ++++++++ .../src/protocol/message_dispatch.rs | 10 +++++ crates/offline-protocol/src/protocol/mod.rs | 9 ++++ .../offline-protocol/src/protocol/prefixes.rs | 9 +++- .../src/protocol/tests/mod.rs | 35 +++++++++++++++ docs/spec/control-messages.md | 44 ++++++++++++++++++- 7 files changed, 140 insertions(+), 5 deletions(-) diff --git a/crates/offline-protocol-sealed/src/prefixes.rs b/crates/offline-protocol-sealed/src/prefixes.rs index 69fe5aedc..e9da6efa6 100644 --- a/crates/offline-protocol-sealed/src/prefixes.rs +++ b/crates/offline-protocol-sealed/src/prefixes.rs @@ -1,10 +1,11 @@ //! The control-frame prefixes a 1:1 sealed conversation is carried on. //! -//! A frame's type is the reserved prefix its content begins with. The seven +//! A frame's type is the reserved prefix its content begins with. The eight //! here are the ones both ends of a pair speak: everything needed to //! establish a session, carry sealed payloads over it, and confirm it came -//! up, and the membership exchange a leaf with a certificate runs like any -//! other node. They live in this crate because a leaf node emits and parses them +//! up, the membership exchange a leaf with a certificate runs like any +//! other node, and the fast link, by which a pair brings up a Wi-Fi network +//! for itself. They live in this crate because a leaf node emits and parses them //! with a different MLS implementation than the engine, and two ends that //! disagree about a prefix byte do not have a conversation at all. //! @@ -70,6 +71,17 @@ pub const SESSION_CONFIRM_ENCRYPTED: &str = "__MLS_ENC_CONFIRM__"; /// [`MemberFrame`]: crate::MemberFrame pub const MEMBER: &str = "__MEMBER__"; +/// Carries one step of a fast link (ADR 0038): a request for one, an offer +/// of a Wi-Fi network's credentials, or its close. Travels **only inside** +/// the decrypted plaintext of an [`ENCRYPTED`] envelope in a confirmed 1:1 +/// session, never on the wire as a frame of its own. +/// +/// Inside, because an offer carries a passphrase: MLS hides it, names the +/// sender and refuses a replayed ciphertext, and a control-plane signature +/// would do only the second. It is a pair's frame like the others here, and a +/// leaf with a Wi-Fi radio can host or join a link as well as a phone can. +pub const FAST_LINK: &str = "__FAST_LINK__"; + #[cfg(test)] mod tests { use super::*; @@ -90,6 +102,7 @@ mod tests { assert_eq!(SESSION_CONFIRM_ACK, "__MLS_CONFIRM_ACK__"); assert_eq!(SESSION_CONFIRM_ENCRYPTED, "__MLS_ENC_CONFIRM__"); assert_eq!(MEMBER, "__MEMBER__"); + assert_eq!(FAST_LINK, "__FAST_LINK__"); } /// No prefix may be a prefix of another. @@ -109,6 +122,7 @@ mod tests { SESSION_CONFIRM_ACK, SESSION_CONFIRM_ENCRYPTED, MEMBER, + FAST_LINK, ]; for (i, a) in all.iter().enumerate() { for (j, b) in all.iter().enumerate() { diff --git a/crates/offline-protocol/src/group_mesh.rs b/crates/offline-protocol/src/group_mesh.rs index 4c63e4199..f6178b8dd 100644 --- a/crates/offline-protocol/src/group_mesh.rs +++ b/crates/offline-protocol/src/group_mesh.rs @@ -1301,6 +1301,12 @@ impl OfflineProtocol { self.handle_group_data_sync_frame(&payload.group_id, sender, &body); return InternalMessageResult::Consumed; } + // A fast-link frame belongs to a 1:1 session (ADR 0038): in a + // group every member would read the passphrase. Consumed, not + // acted on and not shown, on all three arms. + if text.starts_with(internal_prefixes::FAST_LINK) { + return InternalMessageResult::Consumed; + } let msg_id = logical_key.unwrap_or_else(|| message.id.as_str().to_string()); if msg_id != message.id.as_str() { self.group_mesh @@ -2856,6 +2862,15 @@ impl OfflineProtocol { ); continue; } + if text.starts_with(internal_prefixes::FAST_LINK) { + delivered_here.insert(entry.message_id.clone()); + self.ack_drained_group_message( + &entry.sender, + &entry.message_id, + entry.received_via, + ); + continue; + } info!( group_id = %group_id, msg_id = %entry.message_id, @@ -6543,6 +6558,9 @@ impl OfflineProtocol { self.handle_group_data_sync_frame(group_id, sender, &body); return; } + if text.starts_with(internal_prefixes::FAST_LINK) { + return; + } let (content, media_metadata, content_type, forward_info_event) = Self::restore_group_rich(text, forward_info, sender); self.emit_event(Event::group_message_received( diff --git a/crates/offline-protocol/src/protocol/message_dispatch.rs b/crates/offline-protocol/src/protocol/message_dispatch.rs index 2932cc5cd..a5765916c 100644 --- a/crates/offline-protocol/src/protocol/message_dispatch.rs +++ b/crates/offline-protocol/src/protocol/message_dispatch.rs @@ -1623,9 +1623,19 @@ impl OfflineProtocol { "Dropping a sealed service frame that is not a request or response" ); } + // A fast-link frame from a group plaintext never reaches + // here; from this session it is routed below, after the + // confirm, and never surfaced. + let fast_link_frame = (in_session + && text.starts_with(internal_prefixes::FAST_LINK)) + .then(|| std::mem::take(&mut text)); + let stray_fast_link_frame = + !in_session && text.starts_with(internal_prefixes::FAST_LINK); let surfaced = if is_session_confirm || sealed_service_frame.is_some() || unroutable_service_frame + || fast_link_frame.is_some() + || stray_fast_link_frame { Some(InternalMessageResult::Consumed) } else if let Some(body) = text.strip_prefix(internal_prefixes::DATA_V1) { diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index a3eb03b3c..cdf8e4f3f 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -3735,6 +3735,15 @@ impl OfflineProtocol { return Some(InternalMessageResult::Consumed); } + // A fast-link frame (ADR 0038) is routed only from the decrypted + // plaintext of a 1:1 session. One that arrived bare crossed every hop + // readable, offer passphrase and all, so it is consumed and never + // acted on: acting on it would teach a sender that a plaintext offer + // works. Never surfaced either, since it is not application text. + if content.starts_with(internal_prefixes::FAST_LINK) { + return Some(InternalMessageResult::Consumed); + } + // --- Group (mesh/MLS) messages --- if let Some(data) = content.strip_prefix(internal_prefixes::GROUP_MLS_MSG) { diff --git a/crates/offline-protocol/src/protocol/prefixes.rs b/crates/offline-protocol/src/protocol/prefixes.rs index 796d8c891..5ecc0b630 100644 --- a/crates/offline-protocol/src/protocol/prefixes.rs +++ b/crates/offline-protocol/src/protocol/prefixes.rs @@ -1,6 +1,6 @@ //! Internal message prefix definitions and base64 utilities. //! -//! Seven of the prefixes below are defined in `offline-protocol-sealed` and +//! Eight of the prefixes below are defined in `offline-protocol-sealed` and //! named here rather than spelled out: the ones a leaf node also emits and //! parses, with a different MLS implementation. Reservation still happens //! here, because `INTERNAL_PREFIXES` is what refuses application content that @@ -92,6 +92,13 @@ define_internal_prefixes! { /// Consumed on receipt until the exchange is implemented. Defined in /// `offline-protocol-sealed`. MEMBER = offline_protocol_sealed::prefixes::MEMBER, + /// Prefix for a fast-link frame (ADR 0038) inside a decrypted 1:1 MLS + /// plaintext: a request, an offer of a Wi-Fi network's credentials, or a + /// close. Never an outer wire prefix, so not in `DATA_PLANE_PREFIXES`: a + /// bare one on the wire is signature-gated and then consumed, never + /// routed, because an offer's passphrase must have arrived sealed. + /// Defined in `offline-protocol-sealed`. + FAST_LINK = offline_protocol_sealed::prefixes::FAST_LINK, /// Prefix for the sealed rich payload (`RichPayloadV1` JSON) inside a /// decrypted MLS plaintext. Only ever travels INSIDE an `ENCRYPTED` /// envelope, negotiated via `rich_versions` in the key package; listed diff --git a/crates/offline-protocol/src/protocol/tests/mod.rs b/crates/offline-protocol/src/protocol/tests/mod.rs index 1f51f00ff..1fffdd53d 100644 --- a/crates/offline-protocol/src/protocol/tests/mod.rs +++ b/crates/offline-protocol/src/protocol/tests/mod.rs @@ -23652,6 +23652,41 @@ fn a_membership_frame_is_consumed_and_never_answered() { ); } +/// A fast-link frame that arrives bare, outside any session, is consumed: +/// never delivered as application text, never answered and never acted on. +/// An offer carries a passphrase, so one that crossed the air readable is +/// exactly the frame the receiver must not reward (ADR 0038). +#[test] +fn a_bare_fast_link_frame_is_consumed_and_never_answered() { + let mut protocol = OfflineProtocol::new(create_test_config()).unwrap(); + let mock_transport = MockTransport::new(TransportType::BLE); + mock_transport.start().unwrap(); + let sent = mock_transport.clone(); + protocol + .transport_manager_mut() + .add_transport(TransportType::BLE, Box::new(mock_transport)); + protocol.start().unwrap(); + let before = sent.sent_messages().len(); + + let content = format!( + "{}{{\"v\":1,\"kind\":\"offer\",\"link\":\"{}\",\"ssid\":\"DIRECT-ab-0123456789ab\",\ + \"passphrase\":\"{}\",\"host\":\"192.168.49.1\",\"port\":8988,\ + \"issued_at_ms\":0,\"ttl_ms\":120000}}", + internal_prefixes::FAST_LINK, + "a".repeat(32), + "b".repeat(32), + ); + let message = signed_frame(&id("alice"), "user123", &content); + + let result = protocol.process_internal_message(&message); + assert!(matches!(result, Some(InternalMessageResult::Consumed))); + assert_eq!( + sent.sent_messages().len(), + before, + "a bare fast-link frame is never answered" + ); +} + /// No node sends `__MEMBER__` on its own, and above all not on discovery. /// /// A build that does not reserve the prefix rejects the frame with a security diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index 37cbfbb04..70bd64257 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -109,7 +109,7 @@ seconds and an answer over the mesh or a relay can take longer. ### Prefixes that never appear on the wire -Three prefixes are reserved but travel only **inside** an encrypted envelope. They +Four prefixes are reserved but travel only **inside** an encrypted envelope. They are listed in the registry so application content can never impersonate them. | Prefix | Where it lives | Purpose | @@ -117,6 +117,7 @@ are listed in the registry so application content can never impersonate them. | `__MLS_ENC_CONFIRM__` | Inside an `__MLS_ENC__` envelope | A group-aware decrypt that lets the both-create session owner converge. Consumed on receipt, never surfaced to the application | | `__RICH_V1__` | Inside the decrypted MLS plaintext | The sealed rich payload body | | `__DATA_V1__` | Inside the decrypted MLS plaintext | Replicated-document sync frames, negotiated as `data_versions`. See [Document sync frames](#document-sync-frames) | +| `__FAST_LINK__` | Inside the decrypted plaintext of a 1:1 session only | A request for, offer of, or close of a Wi-Fi network for the pair, negotiated as `link_versions`. See [Fast link frames](#fast-link-frames) | ### Connection lifecycle @@ -469,6 +470,47 @@ The prefix itself is registered above, and is subject to every rule in this document: it is an internal prefix, it never appears as an outer wire prefix, and a message body a caller supplies may not begin with it. +## Fast link frames + +`__FAST_LINK__` carries one step of a fast link +([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md), and the +runtime behaviour in [its state machine](../state-machines/fast-link.md)). The +body after the prefix is a JSON object with `"v": 1`, a `kind`, and `link`, a +link id of 32 lowercase hex digits that the device starting the link draws at +random: + +| `kind` | Further fields | Meaning | +|--------|----------------|---------| +| `request` | none | The sender can join a network and asks the recipient to host one | +| `offer` | `ssid`, `passphrase`, `host`, `port`, `issued_at_ms`, `ttl_ms` | The sender is hosting a network for the recipient: join `ssid` with `passphrase` and dial `host:port`, within `ttl_ms` of arrival | +| `close` | `reason` | The link with this id is over | + +Four rules hold for every frame of the family: + +- **Inside a 1:1 session, or not at all.** A sender seals it with the strict + encryptor, which needs a confirmed session and never starts one, and a + receiver routes it only from a decrypted plaintext of a `session:` group. + Found anywhere else (a bare frame on the wire, a group plaintext) it is + consumed and never surfaced. The body carries a passphrase, and that is the + only way it reaches nobody else. +- **Ephemeral.** It is sent once, over a live direct link, with + `requires_ack` false ([ADR 0032](../adr/0032-ephemeral-sends-go-once-over-a-live-link.md)). + A frame that cannot leave now is not sent. Nothing in the family is ever + answered by an acknowledgement, queued, relayed or deposited with a + custodian. +- **Gated by `link_versions` entry 1.** No frame of the family is sent to a + peer that has not advertised it ([Capability negotiation](capability-negotiation.md)). +- **Bounded.** A receiver refuses an offer whose `ssid` is not 1 to 32 bytes, + whose `passphrase` is not 8 to 63 printable ASCII characters, whose `host` is + not an IP literal in a private or link-local range, whose `port` is 0, whose + `ttl_ms` is over 300,000, or whose `issued_at_ms` lies more than 300 s ahead + of its clock or more than `ttl_ms` plus 300 s behind it, and answers it with + a `close` whose `reason` is `invalid`. A `host` is never resolved as a name. + +`reason` is one of `declined`, `failed`, `host_failed`, `cannot_host`, +`cannot_join`, `busy`, `invalid`, `expired`, `no_offer`, `lost`, `idle`, +`background` or `closed`. A receiver treats an unknown reason as `failed`. + ## The control-plane signature gate Control frames are authenticated with an Ed25519 signature over a canonical From 821b78d5ea3d2811cf22cc9122853c7a79611411 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 05:47:15 +0530 Subject: [PATCH 04/81] feat(sealed): advertise the fast-link capability in the key package link_versions entry 1 says a peer routes __fast_link__ frames. it is omitted from the payload when empty, so a key package that does not advertise it is byte for byte what it was, and a leaf advertises nothing. the engine advertises it, records it per peer from each key package, persists it with the other capabilities and restores it at startup. the key package vectors gain a case, and from_advertised now takes the payload rather than one argument per list. --- crates/offline-protocol-leaf/src/keypkg.rs | 3 + .../tests/phone_interop.rs | 9 ++ .../offline-protocol-sealed/src/keypackage.rs | 70 +++++++++++++++- crates/offline-protocol-sealed/src/lib.rs | 2 +- .../tests/data/key-package-v1.vectors.json | 30 +++++++ .../offline-protocol/src/protocol/blocking.rs | 2 + .../src/protocol/message_dispatch.rs | 22 +++-- crates/offline-protocol/src/protocol/mod.rs | 14 ++++ crates/offline-protocol/src/protocol/send.rs | 4 + .../offline-protocol/src/protocol/storage.rs | 6 ++ .../src/protocol/tests/mod.rs | 83 +++++++++++++++++++ .../src/protocol/tests/service_seal.rs | 1 + crates/offline-protocol/src/protocol/types.rs | 62 ++++++-------- docs/spec/capability-negotiation.md | 8 ++ tools/spec-vectors/generate.py | 28 +++++++ 15 files changed, 302 insertions(+), 42 deletions(-) diff --git a/crates/offline-protocol-leaf/src/keypkg.rs b/crates/offline-protocol-leaf/src/keypkg.rs index 1d7a8b83a..264813742 100644 --- a/crates/offline-protocol-leaf/src/keypkg.rs +++ b/crates/offline-protocol-leaf/src/keypkg.rs @@ -134,5 +134,8 @@ pub(crate) fn payload( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + // No fast link: a leaf has no Wi-Fi network to host or join through + // this crate, and saying nothing keeps its key package what it was. + link_versions: Vec::new(), } } diff --git a/crates/offline-protocol-leaf/tests/phone_interop.rs b/crates/offline-protocol-leaf/tests/phone_interop.rs index 38f49ffed..48382aef1 100644 --- a/crates/offline-protocol-leaf/tests/phone_interop.rs +++ b/crates/offline-protocol-leaf/tests/phone_interop.rs @@ -512,6 +512,7 @@ fn a_key_package_that_claims_another_owner_is_refused() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let frame = phone_control_frame( @@ -1144,6 +1145,7 @@ fn a_peer_that_already_has_a_key_package_is_not_sent_another() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let frame = phone_control_frame( &phone, @@ -1730,6 +1732,7 @@ fn a_replayed_session_reset_does_not_tear_down_the_new_session() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let reset_frame = phone_control_frame( &phone, @@ -1831,6 +1834,7 @@ fn a_flood_of_strangers_cannot_displace_an_established_peer() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let frame = phone_control_frame( &phone, @@ -1865,6 +1869,7 @@ fn a_flood_of_strangers_cannot_displace_an_established_peer() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let frame = phone_control_frame( &stranger, @@ -2293,6 +2298,7 @@ fn advertisement_body(user_id: &str) -> String { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; format!( "{}{}", @@ -3224,6 +3230,7 @@ fn a_reset_older_than_the_last_one_acted_on_is_refused() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; phone_control_frame_at( &phone, @@ -3287,6 +3294,7 @@ fn a_spent_reset_stays_spent_across_a_power_cycle() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let reset_frame = phone_control_frame_at( &phone, @@ -3440,6 +3448,7 @@ fn a_session_reset_that_states_no_time_is_refused_its_teardown() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", diff --git a/crates/offline-protocol-sealed/src/keypackage.rs b/crates/offline-protocol-sealed/src/keypackage.rs index 2d6741358..92a1bf16a 100644 --- a/crates/offline-protocol-sealed/src/keypackage.rs +++ b/crates/offline-protocol-sealed/src/keypackage.rs @@ -222,6 +222,33 @@ pub struct KeyPackagePayload { #[serde(default)] pub ack_versions: Vec, + /// Fast-link versions the sender routes (e.g. `[1]` for + /// [`FAST_LINK_V1`]): a [`prefixes::FAST_LINK`] frame found inside a + /// decrypted 1:1 MLS plaintext is handed to its fast-link layer rather + /// than surfaced as a chat message (ADR 0038). Absent on legacy nodes, and + /// toward a peer that advertises nothing here no fast-link frame is ever + /// sent, so it is never asked to host or join and never shown one. + /// + /// It says what the sender parses, not what its platform can do. Whether + /// a device can host or join a network is a property of its radio and its + /// permissions, which change at runtime, so the frames themselves answer + /// that (`cannot_host`, `cannot_join`). + /// + /// End to end, like `rich_versions`: it describes the far end's parser. + /// Omitted when empty, so a payload that does not advertise it is byte + /// for byte what it was. + /// + /// Trust boundary: a plaintext field like the lists above. Stripping it + /// means no fast link with that peer, and the traffic stays on whatever + /// carried it before; forging it onto a peer that cannot parse the frames + /// makes us send it sealed frames it consumes and drops, which only the + /// session could have produced. A feature negotiation, never a security + /// control: what protects an offer is the session it is sealed in. + /// + /// [`prefixes::FAST_LINK`]: crate::prefixes::FAST_LINK + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub link_versions: Vec, + /// This install's Nostr public key (x-only, 64-char lowercase hex), so a /// peer can seal Nostr gift wraps to a key only this install holds. /// @@ -306,6 +333,13 @@ pub const ACK_UNDECRYPTABLE_V1: u8 = 1; /// than it was offered. pub const ACK_COALESCED_V1: u8 = 2; +/// Fast-link version advertised in [`KeyPackagePayload::link_versions`]: the +/// sender routes the `request`, `offer` and `close` frames it finds inside a +/// decrypted 1:1 MLS plaintext under [`prefixes::FAST_LINK`] (ADR 0038). +/// +/// [`prefixes::FAST_LINK`]: crate::prefixes::FAST_LINK +pub const FAST_LINK_V1: u8 = 1; + /// The conformance vectors for the key package payload. /// /// The chapter these pin is `docs/spec/capability-negotiation.md`, and they pin @@ -343,7 +377,7 @@ mod spec_vectors { /// it: a loop over an array a bad merge emptied passes by not running. #[test] fn the_vector_file_is_the_size_it_was() { - assert_eq!(vectors()["parse"].as_array().expect("parse").len(), 4); + assert_eq!(vectors()["parse"].as_array().expect("parse").len(), 5); } #[test] @@ -389,6 +423,7 @@ mod spec_vectors { ("ctrl_versions", &got.ctrl_versions), ("svc_versions", &got.svc_versions), ("ack_versions", &got.ack_versions), + ("link_versions", &got.link_versions), ] { assert_eq!(got, &u8s(&want[field]), "[{name}] {field}"); } @@ -430,6 +465,7 @@ mod spec_vectors { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let rendered = serde_json::to_string(&payload).expect("it serializes"); assert!( @@ -438,6 +474,37 @@ mod spec_vectors { ); } + /// An empty `link_versions` is omitted on the way out, so a key package + /// that advertises no fast link is byte for byte what it was before the + /// field existed: a leaf's, above all, whose frames are counted. + #[test] + fn an_empty_link_list_is_omitted() { + let mut payload = KeyPackagePayload { + user_id: "off1abc".to_string(), + key_package_data: Vec::new(), + remaining_lifetime_ms: 0, + timestamp_ms: 0, + session_reset: false, + no_session: false, + wire_versions: Vec::new(), + env_versions: Vec::new(), + rich_versions: Vec::new(), + data_versions: Vec::new(), + ctrl_versions: Vec::new(), + svc_versions: Vec::new(), + ack_versions: Vec::new(), + nostr_pubkey: None, + link_versions: Vec::new(), + }; + let rendered = serde_json::to_string(&payload).expect("it serializes"); + assert!(!rendered.contains("link_versions"), "{rendered}"); + + payload.link_versions = alloc::vec![FAST_LINK_V1]; + let rendered = serde_json::to_string(&payload).expect("it serializes"); + let back: KeyPackagePayload = serde_json::from_str(&rendered).expect("it parses"); + assert_eq!(back.link_versions, [FAST_LINK_V1]); + } + /// The chapter, or `None` where the repo tree is absent: `cargo package` /// carries `tests/` and the vector file but cannot carry `docs/`. fn chapter() -> Option { @@ -466,6 +533,7 @@ mod spec_vectors { "ctrl_versions", "svc_versions", "ack_versions", + "link_versions", "nostr_pubkey", "session_reset", ] { diff --git a/crates/offline-protocol-sealed/src/lib.rs b/crates/offline-protocol-sealed/src/lib.rs index b6db5dcc0..180651577 100644 --- a/crates/offline-protocol-sealed/src/lib.rs +++ b/crates/offline-protocol-sealed/src/lib.rs @@ -94,7 +94,7 @@ pub use identity_assertion::{ IDENTITY_ASSERTION_MIN_LEN, }; pub use keypackage::{ - KeyPackagePayload, ACK_COALESCED_V1, ACK_UNDECRYPTABLE_V1, CTRL_SIGN_V2, + KeyPackagePayload, ACK_COALESCED_V1, ACK_UNDECRYPTABLE_V1, CTRL_SIGN_V2, FAST_LINK_V1, MLS_ENVELOPE_COMPACT_V1, SVC_SEALED_V1, SVC_SUB_V1, }; pub use membership::{ diff --git a/crates/offline-protocol-sealed/tests/data/key-package-v1.vectors.json b/crates/offline-protocol-sealed/tests/data/key-package-v1.vectors.json index f6d531990..8f1562a3e 100644 --- a/crates/offline-protocol-sealed/tests/data/key-package-v1.vectors.json +++ b/crates/offline-protocol-sealed/tests/data/key-package-v1.vectors.json @@ -34,6 +34,7 @@ "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": null }, "note": "Every absent list defaults to empty, and empty selects the floor. This is rule 2 of capability negotiation expressed as a parse: absence is never an error." @@ -70,6 +71,7 @@ "ack_versions": [ 1 ], + "link_versions": [], "nostr_pubkey": "abcd" }, "note": "data_versions entries are read independently, so [1,2,3] is not a single level." @@ -90,6 +92,7 @@ "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": null }, "note": "An unknown field is ignored rather than refused. A decoder that rejects it cannot be sent a newer key package, which is the frame that carries every other capability." @@ -110,9 +113,36 @@ "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": null }, "note": "Absent and null mean the same thing on the way in. On the way out the field is omitted rather than written null." + }, + { + "name": "a peer that routes fast-link frames", + "json": "{\"user_id\":\"off1abc\",\"key_package_data\":[],\"ack_versions\":[1,2],\"link_versions\":[1]}", + "expect": { + "user_id": "off1abc", + "key_package_data": [], + "remaining_lifetime_ms": 0, + "timestamp_ms": 0, + "session_reset": false, + "wire_versions": [], + "env_versions": [], + "rich_versions": [], + "data_versions": [], + "ctrl_versions": [], + "svc_versions": [], + "ack_versions": [ + 1, + 2 + ], + "link_versions": [ + 1 + ], + "nostr_pubkey": null + }, + "note": "link_versions says what the peer parses, not whether its radio can host or join a network; the fast-link frames answer that. A sender omits the list when it is empty." } ], "emission_is_not_pinned": { diff --git a/crates/offline-protocol/src/protocol/blocking.rs b/crates/offline-protocol/src/protocol/blocking.rs index d51574f95..77fc1c9c3 100644 --- a/crates/offline-protocol/src/protocol/blocking.rs +++ b/crates/offline-protocol/src/protocol/blocking.rs @@ -150,6 +150,7 @@ impl OfflineProtocol { self.peer_ctrl_freshness.remove(user_id); self.peer_undecryptable_ack.remove(user_id); self.peer_coalesced_ack.remove(user_id); + self.peer_fast_link.remove(user_id); self.peer_rich_payload.remove(user_id); self.peer_rich_attested.remove(user_id); // Advertised half only, as above: `svc_sealed_proved_peers` is a @@ -1506,6 +1507,7 @@ mod tests { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = serde_json::to_string(&reset_payload).unwrap(); diff --git a/crates/offline-protocol/src/protocol/message_dispatch.rs b/crates/offline-protocol/src/protocol/message_dispatch.rs index a5765916c..b7cf4d2f9 100644 --- a/crates/offline-protocol/src/protocol/message_dispatch.rs +++ b/crates/offline-protocol/src/protocol/message_dispatch.rs @@ -220,6 +220,22 @@ impl OfflineProtocol { } else { self.peer_coalesced_ack.remove(sender); } + // Record whether this peer routes fast-link frames (ADR 0038). + // Same shape again, and like the ACK lists not gated on our + // config: it says what the peer parses. + if payload + .link_versions + .contains(&offline_protocol_sealed::FAST_LINK_V1) + { + if !self.peer_fast_link.contains(sender) + && self.peer_fast_link.len() >= MAX_KEY_PACKAGE_SENT_TO + { + self.peer_fast_link.clear(); + } + self.peer_fast_link.insert(sender.to_string()); + } else { + self.peer_fast_link.remove(sender); + } // Record whether this peer replicates documents, so the data // layer may push `__DATA_V1__` frames to them. Same shape again: @@ -409,12 +425,8 @@ impl OfflineProtocol { .mark_peer_nostr_pubkey(sender, advertised_nostr_pubkey.as_deref()); let caps = PeerCapabilities::from_advertised( - &payload.env_versions, - &payload.rich_versions, - &payload.data_versions, - &payload.ctrl_versions, + &payload, if signed { &payload.svc_versions } else { &[] }, - &payload.ack_versions, advertised_nostr_pubkey.as_deref(), ); if caps.is_any() { diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index cdf8e4f3f..a468faf97 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -438,6 +438,17 @@ pub struct OfflineProtocol { /// [`ACK_COALESCED_V1`]: offline_protocol_sealed::ACK_COALESCED_V1 pub(crate) peer_coalesced_ack: std::collections::HashSet, + /// Peers that route fast-link frames ([`FAST_LINK_V1`] in + /// `link_versions`, ADR 0038), so a request, offer or close may be sealed + /// to them. Same lifecycle as `peer_undecryptable_ack` above: recorded + /// from each key package, persisted in `PeerCapabilities`, restored at + /// startup. A peer missing here is never sent one, and the only cost of + /// forgetting it is that no fast link is offered until its next key + /// package. + /// + /// [`FAST_LINK_V1`]: offline_protocol_sealed::FAST_LINK_V1 + pub(crate) peer_fast_link: std::collections::HashSet, + /// Delivery ACKs waiting to be coalesced, per peer: the carrier the /// answered frames arrived on, when the first was held, and the answered /// ids with the first one's hop count. Sent as one frame once @@ -1319,6 +1330,7 @@ impl OfflineProtocol { peer_ctrl_freshness: std::collections::HashSet::new(), peer_undecryptable_ack: std::collections::HashSet::new(), peer_coalesced_ack: std::collections::HashSet::new(), + peer_fast_link: std::collections::HashSet::new(), coalesced_acks_out: HashMap::new(), answered_deliveries: HashMap::new(), mesh_resend_generations: HashMap::new(), @@ -1537,6 +1549,7 @@ impl OfflineProtocol { let previous_peer_ctrl_freshness = self.peer_ctrl_freshness.clone(); let previous_peer_undecryptable_ack = self.peer_undecryptable_ack.clone(); let previous_peer_coalesced_ack = self.peer_coalesced_ack.clone(); + let previous_peer_fast_link = self.peer_fast_link.clone(); // Snapshotted with its siblings so a failed re-initialize restores it // too. It is a ratchet, so the direction that matters is that a // rollback must not *lose* it: a peer we hold to the newer payload has @@ -1710,6 +1723,7 @@ impl OfflineProtocol { self.peer_ctrl_freshness = previous_peer_ctrl_freshness; self.peer_undecryptable_ack = previous_peer_undecryptable_ack; self.peer_coalesced_ack = previous_peer_coalesced_ack; + self.peer_fast_link = previous_peer_fast_link; self.control_freshness_peers = previous_control_freshness_peers; self.control_reset_watermark = previous_control_reset_watermark; self.peer_rich_payload = previous_peer_rich_payload; diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index 539693c89..621517f32 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -7042,6 +7042,10 @@ impl OfflineProtocol { offline_protocol_sealed::ACK_COALESCED_V1, ], nostr_pubkey: self.transport_manager.nostr_public_key(), + // Read unconditionally (rule 1 of capability negotiation): whether + // this device can host or join a network is its platform's to + // say, at runtime, and the frames answer that (ADR 0038). + link_versions: vec![offline_protocol_sealed::FAST_LINK_V1], } } diff --git a/crates/offline-protocol/src/protocol/storage.rs b/crates/offline-protocol/src/protocol/storage.rs index e31b4e533..e62d1ae15 100644 --- a/crates/offline-protocol/src/protocol/storage.rs +++ b/crates/offline-protocol/src/protocol/storage.rs @@ -3234,6 +3234,12 @@ impl OfflineProtocol { { self.peer_coalesced_ack.insert(peer_id.clone()); } + if caps + .link_versions + .contains(&offline_protocol_sealed::FAST_LINK_V1) + { + self.peer_fast_link.insert(peer_id.clone()); + } if self.config.encryption.rich_payload_enabled && caps.attested_rich_versions.contains(&RICH_PAYLOAD_V1) { diff --git a/crates/offline-protocol/src/protocol/tests/mod.rs b/crates/offline-protocol/src/protocol/tests/mod.rs index 1fffdd53d..c01d52d9f 100644 --- a/crates/offline-protocol/src/protocol/tests/mod.rs +++ b/crates/offline-protocol/src/protocol/tests/mod.rs @@ -1888,6 +1888,7 @@ fn feed_key_package(protocol: &mut OfflineProtocol, sender: &str, wire_versions: svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -1971,6 +1972,7 @@ fn feed_key_package_with_env(protocol: &mut OfflineProtocol, sender: &str, env_v svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -2170,6 +2172,7 @@ pub(crate) fn feed_key_package_with_capabilities( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -2292,6 +2295,7 @@ fn feed_key_package_with_caps( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -2437,6 +2441,7 @@ fn key_package_message_with_nostr_pubkey( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: nostr_pubkey.map(str::to_string), + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -2775,6 +2780,7 @@ fn feed_key_package_with_data( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -3141,6 +3147,70 @@ fn peer_capability_unblock_clears_record() { ); } +/// `link_versions` is learned from a key package, dropped by one that stops +/// advertising it, and survives a restart like the other capabilities; and +/// this device advertises entry 1 in its own (ADR 0038). +#[test] +fn peer_fast_link_capability_is_learned_and_survives_restart() { + let storage = Arc::new(InMemoryStorage::new()); + let mut protocol = protocol_with_mls_storage(storage.clone()); + let feed = |protocol: &mut OfflineProtocol, sender: &str, link_versions: Vec| { + let payload = KeyPackagePayload { + user_id: sender.to_string(), + key_package_data: vec![1, 2, 3, 4], + remaining_lifetime_ms: 30 * 24 * 60 * 60 * 1000, + timestamp_ms: 0, + session_reset: false, + no_session: false, + wire_versions: Vec::new(), + env_versions: Vec::new(), + rich_versions: Vec::new(), + data_versions: Vec::new(), + ctrl_versions: Vec::new(), + svc_versions: Vec::new(), + ack_versions: Vec::new(), + nostr_pubkey: None, + link_versions, + }; + let content = format!( + "{}{}", + internal_prefixes::KEY_PACKAGE, + serde_json::to_string(&payload).unwrap() + ); + protocol.process_internal_message(&signed_frame(sender, &id("user123"), &content)); + }; + feed( + &mut protocol, + &id("peer"), + vec![offline_protocol_sealed::FAST_LINK_V1], + ); + feed(&mut protocol, &id("legacy"), Vec::new()); + assert!(protocol.peer_fast_link.contains(&id("peer"))); + assert!(!protocol.peer_fast_link.contains(&id("legacy"))); + let bundle = { + let manager = protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager.get_or_create_key_package().unwrap() + }; + assert_eq!( + protocol + .build_key_package_payload(&bundle, false) + .link_versions, + vec![offline_protocol_sealed::FAST_LINK_V1], + "this device routes fast-link frames, and says so" + ); + + let mut restarted = protocol_with_mls_storage(storage.clone()); + assert!(restarted.peer_fast_link.contains(&id("peer"))); + assert!(!restarted.peer_fast_link.contains(&id("legacy"))); + + // A downgrade drops it in memory and on disk. + feed(&mut restarted, &id("peer"), Vec::new()); + assert!(!restarted.peer_fast_link.contains(&id("peer"))); + assert!(!protocol_with_mls_storage(storage) + .peer_fast_link + .contains(&id("peer"))); +} + /// `ack_versions` is learned from a key package, dropped by one that stops /// advertising it, and survives a restart like the other capabilities. #[test] @@ -3163,6 +3233,7 @@ fn peer_undecryptable_ack_capability_is_learned_and_survives_restart() { svc_versions: Vec::new(), ack_versions, nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -3207,6 +3278,7 @@ fn peer_capability_restore_prunes_overflow() { ctrl_versions: Vec::new(), svc_versions: Vec::new(), ack_versions: Vec::new(), + link_versions: Vec::new(), nostr_pubkey: None, }; let encoded = serde_json::to_vec(&caps).unwrap(); @@ -3350,6 +3422,7 @@ fn peer_capability_restore_prefers_session_peers() { ctrl_versions: Vec::new(), svc_versions: Vec::new(), ack_versions: Vec::new(), + link_versions: Vec::new(), nostr_pubkey: None, }; let encoded = serde_json::to_vec(&caps).unwrap(); @@ -3961,6 +4034,7 @@ fn test_process_internal_message_key_package() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -15983,6 +16057,7 @@ fn feed_session_reset_key_package( svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -21086,6 +21161,7 @@ fn test_lamport_clock_merge_on_internal_message() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -21300,6 +21376,7 @@ fn test_key_package_remaining_lifetime_ms() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -21388,6 +21465,7 @@ fn test_peer_key_package_persisted_and_restored_after_restart() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -21479,6 +21557,7 @@ fn test_pending_key_packages_capped_evicts_soonest_to_expire() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -21533,6 +21612,7 @@ fn test_received_key_package_lifetime_is_clamped() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -23090,6 +23170,7 @@ fn test_establish_secure_session_loads_from_storage_after_restart() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", @@ -41413,6 +41494,7 @@ fn key_package_frame_body(sender: &str, session_reset: bool, ctrl_versions: Vec< svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; format!( "{}{}", @@ -43273,6 +43355,7 @@ fn the_ordinary_handshake_starts_a_latency_without_any_session_missing() { svc_versions: Vec::new(), ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; let content = format!( "{}{}", diff --git a/crates/offline-protocol/src/protocol/tests/service_seal.rs b/crates/offline-protocol/src/protocol/tests/service_seal.rs index 8082ed948..5a4cc40e2 100644 --- a/crates/offline-protocol/src/protocol/tests/service_seal.rs +++ b/crates/offline-protocol/src/protocol/tests/service_seal.rs @@ -328,6 +328,7 @@ fn key_package_body(sender: &str, svc_versions: Vec) -> String { svc_versions, ack_versions: Vec::new(), nostr_pubkey: None, + link_versions: Vec::new(), }; serde_json::to_string(&payload).unwrap() } diff --git a/crates/offline-protocol/src/protocol/types.rs b/crates/offline-protocol/src/protocol/types.rs index 4b6f26b8d..1e499a783 100644 --- a/crates/offline-protocol/src/protocol/types.rs +++ b/crates/offline-protocol/src/protocol/types.rs @@ -1639,6 +1639,13 @@ pub(crate) struct PeerCapabilities { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) ack_versions: Vec, + /// Fast-link versions the peer routes, from + /// [`KeyPackagePayload::link_versions`]. Persisted for the same reason as + /// the lists above: without it a peer met before a restart could not be + /// offered a fast link until its next key package. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) link_versions: Vec, + /// The peer's Nostr public key, from [`KeyPackagePayload::nostr_pubkey`]. /// /// Persisted for the same reason as the capability lists: the cached key @@ -1676,48 +1683,32 @@ pub(crate) fn normalize_nostr_pubkey(candidate: &str) -> Option { pub(crate) const MAX_PERSISTED_CAPABILITY_VERSIONS: usize = 8; impl PeerCapabilities { - /// Builds a record from the wire-advertised version lists, truncating - /// each to [`MAX_PERSISTED_CAPABILITY_VERSIONS`]. + /// Builds a record from a key package's advertised version lists, + /// truncating each to [`MAX_PERSISTED_CAPABILITY_VERSIONS`]. + /// + /// `svc_versions` and `nostr_pubkey` come from the caller rather than + /// the payload: both are honoured only from a signed key package, and + /// the caller is the one that knows whether this one was. pub(crate) fn from_advertised( - env_versions: &[u8], - rich_versions: &[u8], - data_versions: &[u8], - ctrl_versions: &[u8], + payload: &KeyPackagePayload, svc_versions: &[u8], - ack_versions: &[u8], nostr_pubkey: Option<&str>, ) -> Self { - Self { - env_versions: env_versions - .iter() - .copied() - .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), - rich_versions: rich_versions - .iter() - .copied() - .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), - data_versions: data_versions + let capped = |versions: &[u8]| -> Vec { + versions .iter() .copied() .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), - ctrl_versions: ctrl_versions - .iter() - .copied() - .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), - svc_versions: svc_versions - .iter() - .copied() - .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), - ack_versions: ack_versions - .iter() - .copied() - .take(MAX_PERSISTED_CAPABILITY_VERSIONS) - .collect(), + .collect() + }; + Self { + env_versions: capped(&payload.env_versions), + rich_versions: capped(&payload.rich_versions), + data_versions: capped(&payload.data_versions), + ctrl_versions: capped(&payload.ctrl_versions), + svc_versions: capped(svc_versions), + ack_versions: capped(&payload.ack_versions), + link_versions: capped(&payload.link_versions), attested_rich_versions: Vec::new(), attested_data_versions: Vec::new(), nostr_pubkey: nostr_pubkey.and_then(normalize_nostr_pubkey), @@ -1733,6 +1724,7 @@ impl PeerCapabilities { || !self.ctrl_versions.is_empty() || !self.svc_versions.is_empty() || !self.ack_versions.is_empty() + || !self.link_versions.is_empty() || !self.attested_rich_versions.is_empty() || !self.attested_data_versions.is_empty() || self.nostr_pubkey.is_some() diff --git a/docs/spec/capability-negotiation.md b/docs/spec/capability-negotiation.md index c5d0a58e3..a214b5add 100644 --- a/docs/spec/capability-negotiation.md +++ b/docs/spec/capability-negotiation.md @@ -14,6 +14,7 @@ Peers advertise what they can parse in the key package payload, the body of a | `ctrl_versions` | End to end | Which control-frame signing payload we build for this peer. Entry 2 means the peer verifies `offline-ctrl-v2`, which binds the frame's timestamp | Build `offline-ctrl-v1`, which states no freshness | | `svc_versions` | End to end | Whether a service request or response may travel sealed inside `__MLS_ENC__` toward this peer. Entry 1 means the peer routes a decrypted `__SVC_REQ__` or `__SVC_RESP__` into its service layer, with the MLS-authenticated sender as the requester. Entry 2 means it routes the four subscription frames from a session slot | Signed plaintext service frames. Without entry 2 from a signed package that has been seen, a subscription is refused at the call; with no package seen, it is tried and ends at its pending timeout | | `ack_versions` | End to end | Which delivery-ACK statuses we may send this peer. Entry 1 means the peer reads `ack_status: "undecryptable"` as "this frame can never decrypt" (it resends the message once, re-sealed when it can) rather than as a delivery. Entry 2 means the peer reads `ack_more`, so one delivery ACK may answer up to five of its frames | Never answer an undecryptable frame; leave it unacknowledged. Acknowledge each frame in its own ACK | +| `link_versions` | End to end | Whether we may send this peer a `__FAST_LINK__` frame. Entry 1 means the peer routes a decrypted `request`, `offer` or `close` into its fast-link layer ([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md)). It says what the peer parses, never whether its radio can host or join a network, which the frames themselves answer. Omitted from the payload when empty | No fast link with that peer | | `nostr_pubkey` | End to end | Which key metadata is sealed to on the Nostr path | Seal to the publicly computable key | The key package payload also carries `user_id`, the MLS key package itself, a @@ -155,6 +156,12 @@ member, which today is entries 2 and 6, read independently. It opens the package from that peer overrides it in both directions. Absence of an attestation means "no information" and MUST NOT be read as a downgrade. +`link_versions` persists with the rest, for the plainer reason: a peer met +before a restart could otherwise not be offered a fast link until its next key +package. It gates no security decision. What protects an offer is the session +it is sealed in, and a forged entry only makes this device send that peer +sealed frames it consumes and drops. + `ack_versions` persists with the rest. A peer that has not advertised entry 1, or whose advertisement this device has not yet received, is sent no `undecryptable` answer at all: an older sender reads any ACK as a delivery, so @@ -310,6 +317,7 @@ A minimal leaf advertises little and works fully: | `ctrl_versions` | `[2]`, always | Not optional, unlike every other row: a leaf verifies the freshness-bound payload on every control frame except `__MLS_KEY_PKG__`, so a peer that never learned this and kept sending the older one would have its Welcome refused and never complete a pairing | | `svc_versions` | Empty | A leaf has no service registry; peers send it signed plaintext service frames, which it never receives in practice | | `ack_versions` | Empty | Peers leave a frame the leaf can never decrypt unanswered rather than answering `undecryptable` | +| `link_versions` | Absent | Peers never offer it a fast link; a leaf has no Wi-Fi network to host or join through the leaf crate | | `nostr_pubkey` | Absent unless the device is reachable over that carrier | Peers seal to the publicly computable key | Two consequences follow from the universal rules above, and both are easy to diff --git a/tools/spec-vectors/generate.py b/tools/spec-vectors/generate.py index 795e2cdea..6da700991 100644 --- a/tools/spec-vectors/generate.py +++ b/tools/spec-vectors/generate.py @@ -1270,6 +1270,7 @@ def build_key_package_vectors() -> dict: "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": None, }, "note": "Every absent list defaults to empty, and empty selects " @@ -1296,6 +1297,7 @@ def build_key_package_vectors() -> dict: "ctrl_versions": [2], "svc_versions": [1], "ack_versions": [1], + "link_versions": [], "nostr_pubkey": "abcd", }, "note": "data_versions entries are read independently, so [1,2,3] " @@ -1318,6 +1320,7 @@ def build_key_package_vectors() -> dict: "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": None, }, "note": "An unknown field is ignored rather than refused. A " @@ -1341,11 +1344,36 @@ def build_key_package_vectors() -> dict: "ctrl_versions": [], "svc_versions": [], "ack_versions": [], + "link_versions": [], "nostr_pubkey": None, }, "note": "Absent and null mean the same thing on the way in. On " "the way out the field is omitted rather than written null.", }, + { + "name": "a peer that routes fast-link frames", + "json": '{"user_id":"off1abc","key_package_data":[],' + '"ack_versions":[1,2],"link_versions":[1]}', + "expect": { + "user_id": "off1abc", + "key_package_data": [], + "remaining_lifetime_ms": 0, + "timestamp_ms": 0, + "session_reset": False, + "wire_versions": [], + "env_versions": [], + "rich_versions": [], + "data_versions": [], + "ctrl_versions": [], + "svc_versions": [], + "ack_versions": [1, 2], + "link_versions": [1], + "nostr_pubkey": None, + }, + "note": "link_versions says what the peer parses, not whether " + "its radio can host or join a network; the fast-link frames " + "answer that. A sender omits the list when it is empty.", + }, ], "emission_is_not_pinned": { "note": "Illustrative only. A conforming peer parses this; it is " From d50844d2c12ed311c1ef2a5b5eec166ea660bef5 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 05:58:34 +0530 Subject: [PATCH 05/81] feat(protocol): run the fast link state machine in the engine crate::fast_link is the state machine of the fast link state machine document, pure and unit-tested for both ends of a pair: roles, credentials drawn fresh per link, offer validation, the lower-address rule when both host, timers, idle teardown, and one close per end. the engine glue gates a request on capability, a confirmed session and a live direct link, seals every frame with the strict encryptor and sends it once with no ack or outbox, routes a decrypted frame from the session, wakes the platform through the peer-stream callback when a directive waits, and emits fast_link_changed, which never carries a credential. --- bindings/react-native/src/types.ts | 28 + .../src/wifi_direct.rs | 8 + crates/offline-protocol/src/events.rs | 55 + crates/offline-protocol/src/fast_link.rs | 1456 +++++++++++++++++ crates/offline-protocol/src/lib.rs | 1 + .../src/protocol/fast_link.rs | 251 +++ .../src/protocol/message_dispatch.rs | 3 + crates/offline-protocol/src/protocol/mod.rs | 9 + crates/offline-protocol/src/protocol/send.rs | 6 + .../src/protocol/tests/fast_link.rs | 272 +++ .../src/protocol/tests/mod.rs | 1 + .../offline-protocol/src/telemetry/record.rs | 9 + .../src/telemetry/scrub_event.rs | 11 + docs/spec/local-api.md | 1 + 14 files changed, 2111 insertions(+) create mode 100644 crates/offline-protocol/src/fast_link.rs create mode 100644 crates/offline-protocol/src/protocol/fast_link.rs create mode 100644 crates/offline-protocol/src/protocol/tests/fast_link.rs diff --git a/bindings/react-native/src/types.ts b/bindings/react-native/src/types.ts index 71297ccfa..7fe5e8102 100644 --- a/bindings/react-native/src/types.ts +++ b/bindings/react-native/src/types.ts @@ -1469,6 +1469,33 @@ export interface TransportSwitchedEvent extends BaseEvent { reason: string; } +/** + * A fast link changed state (ADR 0038): a Wi-Fi network this device hosts + * for a peer, or joins from it, brought up through their session. + * + * `requestFastLink` returns as soon as the first step is taken; this event is + * how the outcome arrives. It never carries a network name or a passphrase. + * Traffic moves onto the link by ordinary transport selection, which + * `transport_switched` reports. + */ +export interface FastLinkChangedEvent extends BaseEvent { + type: 'fast_link_changed'; + /** The peer's canonical address (`off1…`). */ + peer_id: string; + /** The link, 32 lowercase hex digits. */ + link_id: string; + /** This device's side. */ + role: 'host' | 'join'; + /** Where the link is now. */ + state: 'requested' | 'hosting' | 'offered' | 'joining' | 'up' | 'closed'; + /** + * Why it closed, only on `closed`: `declined` (the joiner's user said no), + * `idle`, `lost`, `expired`, `background`, `busy`, `cannot_host`, + * `cannot_join`, and others; an unknown value means it failed. + */ + reason: string | null; +} + /** * Relay promoted event */ @@ -3156,6 +3183,7 @@ export type ProtocolEvent = | MessageFailedEvent | MessageDecryptionFailedEvent | TransportSwitchedEvent + | FastLinkChangedEvent | RelayPromotedEvent | RelayDemotedEvent | RelayDemotedBatteryEvent diff --git a/crates/offline-protocol-transport/src/wifi_direct.rs b/crates/offline-protocol-transport/src/wifi_direct.rs index 3ba0fbb3e..dafb3534b 100644 --- a/crates/offline-protocol-transport/src/wifi_direct.rs +++ b/crates/offline-protocol-transport/src/wifi_direct.rs @@ -169,6 +169,14 @@ impl WifiDirectTransport { } } + /// Wakes the platform as a queued body would, so it drains the engine's + /// fast-link directives (ADR 0038) on the same callback it already + /// drains bodies on. The platform reads both queues every time it is + /// woken, so a wake with no body waiting costs one empty drain. + pub fn wake_platform(&self) { + self.notify_messages_available(); + } + /// Gets the local device ID. pub fn device_id(&self) -> &str { &self.device_id diff --git a/crates/offline-protocol/src/events.rs b/crates/offline-protocol/src/events.rs index 7c3366bad..e82aa5e0c 100644 --- a/crates/offline-protocol/src/events.rs +++ b/crates/offline-protocol/src/events.rs @@ -761,6 +761,28 @@ pub enum Event { reason: String, }, + /// A fast link (ADR 0038) changed state: a Wi-Fi network this device + /// hosts for a peer, or joins from it, brought up through their session. + /// + /// `request_fast_link` returns as soon as its first step is taken; this is + /// how the application learns the outcome. It never carries a network + /// name or a passphrase. The traffic itself moves to the link by the + /// ordinary transport selection, which `TransportSwitched` reports. + FastLinkChanged { + /// The peer's canonical address. + peer_id: String, + /// The link, 32 lowercase hex digits. + link_id: String, + /// `"host"` or `"join"`: this device's side. + role: String, + /// `"requested"`, `"hosting"`, `"offered"`, `"joining"`, `"up"` or + /// `"closed"`. + state: String, + /// Why it closed (`"idle"`, `"declined"`, `"lost"`, ...); only on + /// `"closed"`. + reason: Option, + }, + /// This device started acting as a relay — carrying traffic for other /// devices that cannot reach each other directly. /// @@ -2171,6 +2193,17 @@ impl Event { } } + /// Creates a FastLinkChanged event from the state machine's change. + pub fn fast_link_changed(change: crate::fast_link::FastLinkChange) -> Self { + Self::FastLinkChanged { + peer_id: change.peer_id, + link_id: change.link_id, + role: change.role.as_str().to_string(), + state: change.state.as_str().to_string(), + reason: change.reason.map(|reason| reason.as_str().to_string()), + } + } + /// Creates a RelayPromoted event. pub fn relay_promoted(connection_count: usize, battery_level: Option) -> Self { Self::RelayPromoted { @@ -3033,6 +3066,7 @@ impl Event { Self::MessageFailed { .. } => "protocol.message.failed", Self::MessageDecryptionFailed { .. } => "protocol.message.decryption_failed", Self::TransportSwitched { .. } => "protocol.transport.switched", + Self::FastLinkChanged { .. } => "protocol.fast_link.changed", Self::RelayPromoted { .. } => "protocol.relay.promoted", Self::RelayDemoted { .. } => "protocol.relay.demoted", Self::NeighborDiscovered { .. } => "protocol.neighbor.discovered", @@ -3317,6 +3351,20 @@ impl fmt::Debug for Event { .field("sealed_at_ms", sealed_at_ms) .field("session_established_at_ms", session_established_at_ms) .finish(), + Self::FastLinkChanged { + peer_id: _, + link_id, + role, + state, + reason, + } => f + .debug_struct("FastLinkChanged") + .field("peer_id", &"[REDACTED]") + .field("link_id", link_id) + .field("role", role) + .field("state", state) + .field("reason", reason) + .finish(), Self::TransportSwitched { from, to, reason } => f .debug_struct("TransportSwitched") .field("from", from) @@ -4595,6 +4643,13 @@ mod tests { transport: "BLE".to_string(), rssi: -50, }, + Event::FastLinkChanged { + peer_id: SENTINEL.to_string(), + link_id: "0".repeat(32), + role: "host".to_string(), + state: "closed".to_string(), + reason: Some("idle".to_string()), + }, Event::SecureSessionEstablished { peer_id: SENTINEL.to_string(), group_id: "session:a:b".to_string(), diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs new file mode 100644 index 000000000..76d16f06d --- /dev/null +++ b/crates/offline-protocol/src/fast_link.rs @@ -0,0 +1,1456 @@ +//! The fast link: a Wi-Fi network one device hosts for one peer, whose +//! credentials travel inside their confirmed 1:1 session (ADR 0038). +//! +//! This module is the state machine of `docs/state-machines/fast-link.md` and +//! the `__FAST_LINK__` frame of `docs/spec/control-messages.md`, and nothing +//! else. It holds no engine, no clock and no randomness: every input arrives +//! as an argument, and every output waits in one of three queues the engine +//! drains (frames for the peer, directives for the platform, changes for the +//! application). That is what lets the tests below drive both ends of a pair +//! through every transition without a radio, a session or a timer. +//! +//! The engine glue is `protocol/fast_link.rs`: it seals the frames, checks +//! that a request may be made at all, feeds this machine the stream's proof +//! and loss, and turns changes into events. + +use std::collections::VecDeque; +use std::fmt; +use std::net::IpAddr; + +use offline_protocol_core::time::{Duration, Instant}; +use serde::{Deserialize, Serialize}; + +/// The frame schema version, the `v` of every body. +pub const FAST_LINK_FRAME_VERSION: u8 = 1; + +/// How long an offer stays good, from the moment it is made (host) or +/// arrives (joiner). Covers the user reading the iOS prompt and the ~14 s a +/// join took on the lab pair, with room for a second dial. +pub const OFFER_TTL: Duration = Duration::from_secs(120); + +/// The longest lifetime a receiver accepts on an offer. +pub const MAX_OFFER_TTL_MS: u64 = 300_000; + +/// How far an offer's stated time may disagree with the receiver's clock, +/// beyond its lifetime. Phones disagree by seconds; this bounds only a frame +/// that is plainly not from now. +pub const OFFER_CLOCK_SLACK_MS: i64 = 300_000; + +/// How long a host's platform has to bring its network up. Group creation +/// took 0.15 s on the lab phone. +pub const HOSTING_TIMEOUT: Duration = Duration::from_secs(20); + +/// How long a requester waits for an offer. +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// How long an up link may carry nothing, with no transfer to the peer in +/// flight, before it ends. It costs the joiner its own Wi-Fi. +pub const IDLE_LIMIT: Duration = Duration::from_secs(60); + +/// Hex digits in a link id, 128 bits. +pub const LINK_ID_HEX_LEN: usize = 32; + +/// Hex digits in a passphrase the engine makes, 128 bits. +pub const PASSPHRASE_HEX_LEN: usize = 32; + +/// The largest body after the prefix a receiver parses. An offer is about +/// 250 bytes. +pub const MAX_FRAME_BODY_BYTES: usize = 2048; + +/// What this device's platform can do. Both false until it says otherwise. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FastLinkRoles { + /// It can bring up a network for a peer and admit only that peer. + pub can_host: bool, + /// It can join a network by name and passphrase and dial an address on it. + pub can_join: bool, +} + +/// Which side of a link this device is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FastLinkRole { + /// It brought the network up. + Host, + /// It joins the network the peer brought up. + Join, +} + +impl FastLinkRole { + /// The token events carry. + pub fn as_str(self) -> &'static str { + match self { + Self::Host => "host", + Self::Join => "join", + } + } +} + +/// Where a link is. The six states of the state machine. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FastLinkState { + /// A request is out; waiting for an offer. + Requested, + /// The platform is bringing a network up. + Hosting, + /// The offer is out; waiting for the peer's stream. + Offered, + /// The platform is joining the offered network. + Joining, + /// A stream proved the peer. + Up, + /// Over. + Closed, +} + +impl FastLinkState { + /// The token events carry. + pub fn as_str(self) -> &'static str { + match self { + Self::Requested => "requested", + Self::Hosting => "hosting", + Self::Offered => "offered", + Self::Joining => "joining", + Self::Up => "up", + Self::Closed => "closed", + } + } +} + +/// Why a link ended, the `reason` of a `close` frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CloseReason { + /// The joiner's user declined the network. + Declined, + /// Something failed that has no more specific reason. + Failed, + /// The host's platform did not bring its network up. + HostFailed, + /// The peer cannot host. + CannotHost, + /// The peer cannot join. + CannotJoin, + /// The peer holds a link with someone else. + Busy, + /// An offer failed validation. + Invalid, + /// The offer's lifetime ran out before a stream proved the peer. + Expired, + /// No offer answered a request in time. + NoOffer, + /// The stream over the link ended. + Lost, + /// The link carried nothing for [`IDLE_LIMIT`]. + Idle, + /// The joiner's application left the foreground and its platform drops + /// the network. + Background, + /// The application closed it. + Closed, +} + +impl CloseReason { + /// The wire token. + pub fn as_str(self) -> &'static str { + match self { + Self::Declined => "declined", + Self::Failed => "failed", + Self::HostFailed => "host_failed", + Self::CannotHost => "cannot_host", + Self::CannotJoin => "cannot_join", + Self::Busy => "busy", + Self::Invalid => "invalid", + Self::Expired => "expired", + Self::NoOffer => "no_offer", + Self::Lost => "lost", + Self::Idle => "idle", + Self::Background => "background", + Self::Closed => "closed", + } + } + + /// Reads a wire or platform token. An unknown one is `failed`, so a + /// later release's reason still ends the link. + pub fn parse(token: &str) -> Self { + match token { + "declined" => Self::Declined, + "host_failed" => Self::HostFailed, + "cannot_host" => Self::CannotHost, + "cannot_join" => Self::CannotJoin, + "busy" => Self::Busy, + "invalid" => Self::Invalid, + "expired" => Self::Expired, + "no_offer" => Self::NoOffer, + "lost" => Self::Lost, + "idle" => Self::Idle, + "background" => Self::Background, + "closed" => Self::Closed, + _ => Self::Failed, + } + } +} + +/// One `__FAST_LINK__` body. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct Frame { + pub(crate) v: u8, + pub(crate) link: String, + #[serde(flatten)] + pub(crate) body: FrameBody, +} + +/// The three kinds. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum FrameBody { + Request, + Offer(Offer), + Close { reason: String }, +} + +/// What an offer names. +#[derive(Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct Offer { + pub(crate) ssid: String, + pub(crate) passphrase: String, + pub(crate) host: String, + pub(crate) port: u16, + pub(crate) issued_at_ms: i64, + pub(crate) ttl_ms: u64, +} + +impl fmt::Debug for Offer { + // Never the passphrase, in any log (invariant 5). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Offer") + .field("ssid", &self.ssid) + .field("passphrase", &"[REDACTED]") + .field("host", &self.host) + .field("port", &self.port) + .field("issued_at_ms", &self.issued_at_ms) + .field("ttl_ms", &self.ttl_ms) + .finish() + } +} + +impl Frame { + fn new(link: &str, body: FrameBody) -> Self { + Self { + v: FAST_LINK_FRAME_VERSION, + link: link.to_string(), + body, + } + } + + /// The body after the prefix. + pub(crate) fn encode(&self) -> String { + // A struct of strings and integers always serializes. + serde_json::to_string(self).unwrap_or_default() + } + + /// Parses a body after the prefix. `None` for anything this version does + /// not speak: another `v`, a malformed link id, an oversized body. + pub(crate) fn parse(body: &str) -> Option { + if body.len() > MAX_FRAME_BODY_BYTES { + return None; + } + let frame: Self = serde_json::from_str(body).ok()?; + (frame.v == FAST_LINK_FRAME_VERSION && is_link_id(&frame.link)).then_some(frame) + } +} + +/// A link id: 32 lowercase hex digits. +pub(crate) fn is_link_id(id: &str) -> bool { + id.len() == LINK_ID_HEX_LEN && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// Whether `host` is an address a joiner may dial: an IP literal in a private +/// or link-local range, so an offer can never name a host to resolve or a +/// route off the network just joined. +pub(crate) fn is_local_host(host: &str) -> bool { + match host.parse::() { + Ok(IpAddr::V4(v4)) => v4.is_private() || v4.is_link_local(), + Ok(IpAddr::V6(v6)) => { + let first = v6.segments()[0]; + // fc00::/7 unique local, fe80::/10 link local. + (first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80 + } + Err(_) => false, + } +} + +impl Offer { + /// The bounds of the control-messages chapter, against the receiver's + /// clock. + pub(crate) fn is_valid(&self, now_ms: i64) -> bool { + let ssid_ok = (1..=32).contains(&self.ssid.len()); + let passphrase_ok = (8..=63).contains(&self.passphrase.len()) + && self.passphrase.bytes().all(|b| (0x20..=0x7e).contains(&b)); + let ttl_ok = self.ttl_ms > 0 && self.ttl_ms <= MAX_OFFER_TTL_MS; + // ttl_ms is at most MAX_OFFER_TTL_MS here, so the cast is exact. + let oldest = now_ms - self.ttl_ms as i64 - OFFER_CLOCK_SLACK_MS; + let newest = now_ms + OFFER_CLOCK_SLACK_MS; + let time_ok = ttl_ok && (oldest..=newest).contains(&self.issued_at_ms); + ssid_ok && passphrase_ok && is_local_host(&self.host) && self.port != 0 && time_ok + } +} + +/// A link id and credentials, drawn by the engine from its random source. +#[derive(Clone, PartialEq, Eq)] +pub struct FreshLink { + /// 32 lowercase hex digits. + pub link_id: String, + /// `DIRECT-xy-` and twelve hex digits. + pub ssid: String, + /// 32 hex digits. + pub passphrase: String, +} + +impl fmt::Debug for FreshLink { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FreshLink") + .field("link_id", &self.link_id) + .field("ssid", &self.ssid) + .field("passphrase", &"[REDACTED]") + .finish() + } +} + +impl FreshLink { + /// Draws one from `fill`, which must be a cryptographic random source. + /// + /// The name is `DIRECT-` (Android requires it, and two characters after + /// it), two random characters, `-` and twelve random hex digits: random, + /// so nothing on the air derives from the application, the user or the + /// device (ADR 0037). The passphrase is 128 bits. + pub fn generate(mut fill: impl FnMut(&mut [u8])) -> Self { + const ALNUM: &[u8; 36] = b"abcdefghijklmnopqrstuvwxyz0123456789"; + let mut id = [0u8; LINK_ID_HEX_LEN / 2]; + let mut pass = [0u8; PASSPHRASE_HEX_LEN / 2]; + let mut tag = [0u8; 2]; + let mut name = [0u8; 6]; + fill(&mut id); + fill(&mut pass); + fill(&mut tag); + fill(&mut name); + let tag: String = tag + .iter() + .map(|b| ALNUM[usize::from(*b) % ALNUM.len()] as char) + .collect(); + Self { + link_id: hex::encode(id), + ssid: format!("DIRECT-{tag}-{}", hex::encode(name)), + passphrase: hex::encode(pass), + } + } +} + +/// What the platform is told to do. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FastLinkDirectiveKind { + /// Bring up a network with the given name and passphrase, admitting only + /// the given peer, and report its address and port. + Host, + /// Join the given network and dial `host:port`, claiming the given peer. + Join, + /// End whatever this device holds for the link. + Close, +} + +impl FastLinkDirectiveKind { + /// The token the platform reads. + pub fn as_str(self) -> &'static str { + match self { + Self::Host => "host", + Self::Join => "join", + Self::Close => "close", + } + } +} + +/// One instruction for the platform. +#[derive(Clone, PartialEq, Eq)] +pub struct FastLinkDirective { + /// What to do. + pub kind: FastLinkDirectiveKind, + /// The link it is for. + pub link_id: String, + /// The peer: the only address a host admits, and the address a joiner's + /// stream must prove. + pub peer_id: String, + /// The network's name (`host`, `join`). + pub ssid: Option, + /// The network's passphrase (`host`, `join`). + pub passphrase: Option, + /// The address to dial (`join`). + pub host: Option, + /// The port to dial (`join`). + pub port: Option, + /// How long the platform has: to bring the network up (`host`), or to + /// prove the stream (`join`). Zero on `close`. + pub expires_in_ms: u64, + /// Why (`close`). + pub reason: Option, +} + +impl fmt::Debug for FastLinkDirective { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("FastLinkDirective") + .field("kind", &self.kind) + .field("link_id", &self.link_id) + .field("peer_id", &"[REDACTED]") + .field("ssid", &self.ssid) + .field( + "passphrase", + &self.passphrase.as_ref().map(|_| "[REDACTED]"), + ) + .field("host", &self.host) + .field("port", &self.port) + .field("expires_in_ms", &self.expires_in_ms) + .field("reason", &self.reason) + .finish() + } +} + +/// A transition the application hears about. Never a credential. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FastLinkChange { + /// The peer. + pub peer_id: String, + /// The link. + pub link_id: String, + /// This device's side. + pub role: FastLinkRole, + /// Where the link is now. + pub state: FastLinkState, + /// Why it closed. + pub reason: Option, +} + +/// Why a request was refused before anything was sent. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FastLinkRefusal { + /// This device can neither host nor join. + Unsupported, + /// A link with another peer is in progress or up. + Busy, +} + +/// A directive and the instant its `expires_in_ms` counts down to. +#[derive(Debug, Clone)] +struct PendingDirective { + directive: FastLinkDirective, + deadline: Option, +} + +#[derive(Debug, Clone)] +struct Link { + id: String, + peer: String, + role: FastLinkRole, + state: FastLinkState, + /// When the current state ends by itself. + deadline: Option, + last_activity: Instant, + /// The host's credentials, until the offer is made. + credentials: Option<(String, String)>, + /// The host's offer, kept to answer a repeated request. + offer: Option, + /// The platform holds something for this link, so its end needs a + /// `close` directive. + platform_engaged: bool, + /// The peer knows of this link, so its end needs a `close` frame. + peer_engaged: bool, +} + +/// The machine. One link at a time (invariant 3). +#[derive(Debug, Default)] +pub(crate) struct FastLinks { + roles: FastLinkRoles, + link: Option, + directives: VecDeque, + frames: VecDeque<(String, Frame)>, + changes: VecDeque, +} + +impl FastLinks { + pub(crate) fn set_roles(&mut self, roles: FastLinkRoles) { + self.roles = roles; + } + + /// The peer of the link in progress, if any. + pub(crate) fn peer(&self) -> Option<&str> { + self.link.as_ref().map(|link| link.peer.as_str()) + } + + /// The application asks for a link to `peer`. Returns the link id. + pub(crate) fn request( + &mut self, + peer: &str, + fresh: FreshLink, + now: Instant, + ) -> Result { + if let Some(link) = &self.link { + return if link.peer == peer { + Ok(link.id.clone()) + } else { + Err(FastLinkRefusal::Busy) + }; + } + if self.roles.can_host { + let id = fresh.link_id.clone(); + self.start_host(peer, fresh, now, false); + return Ok(id); + } + if !self.roles.can_join { + return Err(FastLinkRefusal::Unsupported); + } + let id = fresh.link_id; + self.frames + .push_back((peer.to_string(), Frame::new(&id, FrameBody::Request))); + self.link = Some(Link { + id: id.clone(), + peer: peer.to_string(), + role: FastLinkRole::Join, + state: FastLinkState::Requested, + deadline: Some(now + REQUEST_TIMEOUT), + last_activity: now, + credentials: None, + offer: None, + platform_engaged: false, + peer_engaged: true, + }); + self.changed(None); + Ok(id) + } + + fn start_host(&mut self, peer: &str, fresh: FreshLink, now: Instant, peer_engaged: bool) { + self.directives.push_back(PendingDirective { + directive: FastLinkDirective { + kind: FastLinkDirectiveKind::Host, + link_id: fresh.link_id.clone(), + peer_id: peer.to_string(), + ssid: Some(fresh.ssid.clone()), + passphrase: Some(fresh.passphrase.clone()), + host: None, + port: None, + expires_in_ms: 0, + reason: None, + }, + deadline: Some(now + HOSTING_TIMEOUT), + }); + self.link = Some(Link { + id: fresh.link_id, + peer: peer.to_string(), + role: FastLinkRole::Host, + state: FastLinkState::Hosting, + deadline: Some(now + HOSTING_TIMEOUT), + last_activity: now, + credentials: Some((fresh.ssid, fresh.passphrase)), + offer: None, + platform_engaged: true, + peer_engaged, + }); + self.changed(None); + } + + /// The host's platform has its network up at `host:port`. + pub(crate) fn hosting( + &mut self, + link_id: &str, + host: &str, + port: u16, + now: Instant, + now_ms: i64, + ) -> bool { + let ours = self.link.as_ref().is_some_and(|link| { + link.id == link_id + && link.role == FastLinkRole::Host + && link.state == FastLinkState::Hosting + && link.credentials.is_some() + }); + if !ours { + return false; + } + if !is_local_host(host) || port == 0 { + self.end(CloseReason::HostFailed, true); + return false; + } + let Some(link) = self.link.as_mut() else { + return false; + }; + let Some((ssid, passphrase)) = link.credentials.take() else { + return false; + }; + let offer = Offer { + ssid, + passphrase, + host: host.to_string(), + port, + issued_at_ms: now_ms, + ttl_ms: OFFER_TTL.as_millis() as u64, + }; + link.state = FastLinkState::Offered; + link.deadline = Some(now + OFFER_TTL); + link.peer_engaged = true; + link.offer = Some(offer.clone()); + let frame = Frame::new(&link.id, FrameBody::Offer(offer)); + let peer = link.peer.clone(); + self.frames.push_back((peer, frame)); + self.changed(None); + true + } + + /// A frame from `peer`, who is its MLS-authenticated sender. + pub(crate) fn on_frame( + &mut self, + peer: &str, + local: &str, + frame: Frame, + fresh: FreshLink, + now: Instant, + now_ms: i64, + ) { + match frame.body { + FrameBody::Request => self.on_request(peer, &frame.link, fresh, now), + FrameBody::Offer(offer) => self.on_offer(peer, local, &frame.link, offer, now, now_ms), + FrameBody::Close { reason } => { + if self + .link + .as_ref() + .is_some_and(|link| link.id == frame.link && link.peer == peer) + { + self.end(CloseReason::parse(&reason), false); + } + } + } + } + + fn reply_close(&mut self, peer: &str, link: &str, reason: CloseReason) { + self.frames.push_back(( + peer.to_string(), + Frame::new( + link, + FrameBody::Close { + reason: reason.as_str().to_string(), + }, + ), + )); + } + + fn on_request(&mut self, peer: &str, link_id: &str, fresh: FreshLink, now: Instant) { + if let Some(link) = self.link.clone() { + if link.peer != peer { + self.reply_close(peer, link_id, CloseReason::Busy); + return; + } + match (link.role, link.state, link.offer) { + // The request means our offer was lost: send it again. + (FastLinkRole::Host, FastLinkState::Offered, Some(offer)) => { + let frame = Frame::new(&link.id, FrameBody::Offer(offer)); + self.frames.push_back((peer.to_string(), frame)); + } + // Our offer follows once the network is up. + (FastLinkRole::Host, _, _) => {} + // Each asked the other to host: neither can. + (FastLinkRole::Join, _, _) => { + self.reply_close(peer, link_id, CloseReason::CannotHost); + } + } + return; + } + if !self.roles.can_host { + self.reply_close(peer, link_id, CloseReason::CannotHost); + return; + } + // Under the requester's id, so its close and our offer name one link. + let fresh = FreshLink { + link_id: link_id.to_string(), + ..fresh + }; + self.start_host(peer, fresh, now, true); + } + + fn on_offer( + &mut self, + peer: &str, + local: &str, + link_id: &str, + offer: Offer, + now: Instant, + now_ms: i64, + ) { + if !offer.is_valid(now_ms) { + self.reply_close(peer, link_id, CloseReason::Invalid); + return; + } + if let Some(link) = self.link.clone() { + if link.peer != peer { + self.reply_close(peer, link_id, CloseReason::Busy); + return; + } + match link.role { + FastLinkRole::Host => { + // Both are hosting for each other. The lower address + // keeps hosting; the higher closes its own and joins. + if local.as_bytes() < peer.as_bytes() { + return; + } + self.end(CloseReason::Busy, true); + } + FastLinkRole::Join => { + if link.id == link_id && link.state != FastLinkState::Requested { + // A repeat of the offer this link already acts on. + return; + } + if link.state != FastLinkState::Requested { + // A new offer replaces the one before it: the host + // brought up a new network. Nothing to tell it. + self.end(CloseReason::Failed, false); + } else { + // The offer answers our request; it supersedes the + // request's link quietly, whatever id the host chose. + self.link = None; + } + } + } + } + if !self.roles.can_join { + self.reply_close(peer, link_id, CloseReason::CannotJoin); + return; + } + let ttl = Duration::from_millis(offer.ttl_ms.min(MAX_OFFER_TTL_MS)); + self.directives.push_back(PendingDirective { + directive: FastLinkDirective { + kind: FastLinkDirectiveKind::Join, + link_id: link_id.to_string(), + peer_id: peer.to_string(), + ssid: Some(offer.ssid), + passphrase: Some(offer.passphrase), + host: Some(offer.host), + port: Some(offer.port), + expires_in_ms: 0, + reason: None, + }, + deadline: Some(now + ttl), + }); + self.link = Some(Link { + id: link_id.to_string(), + peer: peer.to_string(), + role: FastLinkRole::Join, + state: FastLinkState::Joining, + deadline: Some(now + ttl), + last_activity: now, + credentials: None, + offer: None, + platform_engaged: true, + peer_engaged: true, + }); + self.changed(None); + } + + /// The platform could not do what it was told, or can no longer hold the + /// link. It already let go, so no `close` directive follows. + pub(crate) fn platform_ended(&mut self, link_id: &str, reason: CloseReason) -> bool { + match self.link.as_mut() { + Some(link) if link.id == link_id => { + link.platform_engaged = false; + self.end(reason, true); + true + } + _ => false, + } + } + + /// The application ends the link with `peer`. + pub(crate) fn close(&mut self, peer: &str) -> bool { + if self.peer() != Some(peer) { + return false; + } + self.end(CloseReason::Closed, true); + true + } + + /// A stream proved `peer`. + pub(crate) fn stream_proved(&mut self, peer: &str, now: Instant) { + let Some(link) = self.link.as_mut() else { + return; + }; + if link.peer == peer + && matches!(link.state, FastLinkState::Offered | FastLinkState::Joining) + { + link.state = FastLinkState::Up; + link.deadline = None; + link.last_activity = now; + self.changed(None); + } + } + + /// The stream that proved `peer` ended. + pub(crate) fn stream_lost(&mut self, peer: &str) { + if self + .link + .as_ref() + .is_some_and(|link| link.peer == peer && link.state == FastLinkState::Up) + { + self.end(CloseReason::Lost, true); + } + } + + /// The slot carried a body for `peer`. + pub(crate) fn activity(&mut self, peer: &str, now: Instant) { + if let Some(link) = self.link.as_mut() { + if link.peer == peer { + link.last_activity = now; + } + } + } + + /// Runs the timers. `busy` says whether a transfer to the link's peer is + /// in flight, which holds the idle limit off. + pub(crate) fn tick(&mut self, now: Instant, busy: impl FnOnce(&str) -> bool) { + let Some(link) = self.link.as_mut() else { + return; + }; + let due = link.deadline.is_some_and(|deadline| now >= deadline); + let reason = match link.state { + FastLinkState::Hosting if due => Some(CloseReason::HostFailed), + FastLinkState::Offered | FastLinkState::Joining if due => Some(CloseReason::Expired), + FastLinkState::Requested if due => Some(CloseReason::NoOffer), + FastLinkState::Up => { + if busy(&link.peer) { + link.last_activity = now; + None + } else if now.saturating_duration_since(link.last_activity) >= IDLE_LIMIT { + Some(CloseReason::Idle) + } else { + None + } + } + _ => None, + }; + if let Some(reason) = reason { + self.end(reason, true); + } + } + + /// Ends the link: a `close` directive when the platform holds something, + /// a `close` frame when the peer knows of it and `tell_peer`, and one + /// change (invariant 4). + fn end(&mut self, reason: CloseReason, tell_peer: bool) { + let Some(link) = self.link.take() else { + return; + }; + if link.platform_engaged { + self.directives.push_back(PendingDirective { + directive: FastLinkDirective { + kind: FastLinkDirectiveKind::Close, + link_id: link.id.clone(), + peer_id: link.peer.clone(), + ssid: None, + passphrase: None, + host: None, + port: None, + expires_in_ms: 0, + reason: Some(reason), + }, + deadline: None, + }); + } + if tell_peer && link.peer_engaged { + self.reply_close(&link.peer, &link.id, reason); + } + self.changes.push_back(FastLinkChange { + peer_id: link.peer, + link_id: link.id, + role: link.role, + state: FastLinkState::Closed, + reason: Some(reason), + }); + } + + fn changed(&mut self, reason: Option) { + if let Some(link) = &self.link { + self.changes.push_back(FastLinkChange { + peer_id: link.peer.clone(), + link_id: link.id.clone(), + role: link.role, + state: link.state, + reason, + }); + } + } + + pub(crate) fn has_directives(&self) -> bool { + !self.directives.is_empty() + } + + /// The next directive, its lifetime counted from `now`. + pub(crate) fn next_directive(&mut self, now: Instant) -> Option { + let pending = self.directives.pop_front()?; + let mut directive = pending.directive; + directive.expires_in_ms = pending + .deadline + .map(|deadline| deadline.saturating_duration_since(now).as_millis() as u64) + .unwrap_or(0); + Some(directive) + } + + pub(crate) fn take_frames(&mut self) -> Vec<(String, Frame)> { + self.frames.drain(..).collect() + } + + pub(crate) fn take_changes(&mut self) -> Vec { + self.changes.drain(..).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const LOW: &str = "off1aaaa"; + const HIGH: &str = "off1zzzz"; + + fn fresh(seed: u8) -> FreshLink { + let mut n = seed; + FreshLink::generate(|buf| { + for byte in buf { + *byte = n; + n = n.wrapping_add(1); + } + }) + } + + fn host_roles() -> FastLinkRoles { + FastLinkRoles { + can_host: true, + can_join: true, + } + } + + fn join_roles() -> FastLinkRoles { + FastLinkRoles { + can_host: false, + can_join: true, + } + } + + fn machine(roles: FastLinkRoles) -> FastLinks { + let mut links = FastLinks::default(); + links.set_roles(roles); + links + } + + /// Carries every frame `from` queued to `to`, as the session would. + fn deliver( + from: &mut FastLinks, + from_addr: &str, + to: &mut FastLinks, + to_addr: &str, + now: Instant, + now_ms: i64, + ) -> usize { + let frames = from.take_frames(); + let count = frames.len(); + for (recipient, frame) in frames { + assert_eq!(recipient, to_addr); + let wire = frame.encode(); + let parsed = Frame::parse(&wire).expect("every frame we send parses"); + to.on_frame(from_addr, to_addr, parsed, fresh(99), now, now_ms); + } + count + } + + fn states(links: &mut FastLinks) -> Vec { + links.take_changes().into_iter().map(|c| c.state).collect() + } + + #[test] + fn credentials_are_random_shaped_and_never_logged() { + let link = fresh(7); + assert!(is_link_id(&link.link_id)); + assert_eq!(link.passphrase.len(), PASSPHRASE_HEX_LEN); + assert!(link.ssid.starts_with("DIRECT-")); + assert_eq!(link.ssid.len(), 22); + assert_eq!(&link.ssid[9..10], "-"); + assert!(link.ssid.len() <= 32); + assert_ne!(fresh(7).passphrase, fresh(8).passphrase); + let shown = format!("{link:?}"); + assert!(!shown.contains(&link.passphrase), "{shown}"); + } + + #[test] + fn an_android_requester_hosts_and_an_iphone_joins() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + + let id = android.request(HIGH, fresh(1), t0).unwrap(); + assert_eq!(states(&mut android), [FastLinkState::Hosting]); + let host = android.next_directive(t0).unwrap(); + assert_eq!(host.kind, FastLinkDirectiveKind::Host); + assert_eq!(host.peer_id, HIGH); + assert_eq!(host.expires_in_ms, HOSTING_TIMEOUT.as_millis() as u64); + // Nothing reaches the peer before the network is up. + assert!(android.take_frames().is_empty()); + + assert!(android.hosting(&id, "192.168.49.1", 8988, t0, 1_000)); + assert_eq!(states(&mut android), [FastLinkState::Offered]); + assert_eq!(deliver(&mut android, LOW, &mut iphone, HIGH, t0, 1_000), 1); + + let join = iphone.next_directive(t0).unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, id); + assert_eq!(join.peer_id, LOW); + assert_eq!(join.ssid, host.ssid); + assert_eq!(join.passphrase, host.passphrase); + assert_eq!(join.host.as_deref(), Some("192.168.49.1")); + assert_eq!(join.port, Some(8988)); + assert_eq!(join.expires_in_ms, OFFER_TTL.as_millis() as u64); + assert_eq!(states(&mut iphone), [FastLinkState::Joining]); + + android.stream_proved(HIGH, t0); + iphone.stream_proved(LOW, t0); + assert_eq!(states(&mut android), [FastLinkState::Up]); + assert_eq!(states(&mut iphone), [FastLinkState::Up]); + } + + #[test] + fn an_iphone_requester_asks_the_android_to_host() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + + let id = iphone.request(LOW, fresh(1), t0).unwrap(); + assert_eq!(states(&mut iphone), [FastLinkState::Requested]); + assert!( + !iphone.has_directives(), + "a requester's platform has nothing to do yet" + ); + deliver(&mut iphone, HIGH, &mut android, LOW, t0, 0); + + let host = android.next_directive(t0).unwrap(); + assert_eq!(host.kind, FastLinkDirectiveKind::Host); + assert_eq!(host.link_id, id, "the host answers under the request's id"); + assert!(android.hosting(&id, "192.168.49.1", 8988, t0, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, t0, 0); + + let join = iphone.next_directive(t0).unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(states(&mut iphone), [FastLinkState::Joining]); + } + + #[test] + fn a_device_that_can_do_neither_refuses_at_the_call() { + let mut links = machine(FastLinkRoles::default()); + assert_eq!( + links.request(HIGH, fresh(1), Instant::now()), + Err(FastLinkRefusal::Unsupported) + ); + assert!(links.take_frames().is_empty()); + } + + #[test] + fn a_second_peer_is_refused_while_a_link_is_held() { + let t0 = Instant::now(); + let mut links = machine(host_roles()); + let id = links.request(HIGH, fresh(1), t0).unwrap(); + assert_eq!(links.request(HIGH, fresh(2), t0), Ok(id)); + assert_eq!( + links.request("off1other", fresh(3), t0), + Err(FastLinkRefusal::Busy) + ); + + // A peer's request is answered busy, under its own id. + let other = fresh(4).link_id; + links.on_frame( + "off1other", + LOW, + Frame::new(&other, FrameBody::Request), + fresh(5), + t0, + 0, + ); + let frames = links.take_frames(); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0].0, "off1other"); + assert_eq!(frames[0].1.link, other); + assert_eq!( + frames[0].1.body, + FrameBody::Close { + reason: "busy".to_string() + } + ); + } + + #[test] + fn a_device_that_cannot_host_answers_a_request_so() { + let mut iphone = machine(join_roles()); + let id = fresh(1).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Request), + fresh(2), + Instant::now(), + 0, + ); + let frames = iphone.take_frames(); + assert_eq!( + frames[0].1.body, + FrameBody::Close { + reason: "cannot_host".to_string() + } + ); + assert!(iphone.peer().is_none()); + } + + #[test] + fn two_hosts_racing_leave_the_lower_address_hosting() { + let t0 = Instant::now(); + let mut low = machine(host_roles()); + let mut high = machine(host_roles()); + let low_id = low.request(HIGH, fresh(1), t0).unwrap(); + let high_id = high.request(LOW, fresh(2), t0).unwrap(); + low.next_directive(t0); + high.next_directive(t0); + assert!(low.hosting(&low_id, "192.168.49.1", 8988, t0, 0)); + assert!(high.hosting(&high_id, "192.168.49.1", 8988, t0, 0)); + low.take_changes(); + high.take_changes(); + + // Each receives the other's offer. + let from_low = low.take_frames(); + let from_high = high.take_frames(); + for (_, frame) in from_high { + low.on_frame(HIGH, LOW, frame, fresh(3), t0, 0); + } + for (_, frame) in from_low { + high.on_frame(LOW, HIGH, frame, fresh(4), t0, 0); + } + + assert!( + low.take_frames().is_empty(), + "the lower one ignores the offer" + ); + assert_eq!(low.peer(), Some(HIGH)); + + // The higher one closed its own (platform and peer) and joins. + let closes: Vec<_> = high.take_frames(); + assert_eq!(closes.len(), 1); + assert_eq!(closes[0].1.link, high_id); + let close = high.next_directive(t0).unwrap(); + assert_eq!(close.kind, FastLinkDirectiveKind::Close); + assert_eq!(close.link_id, high_id); + let join = high.next_directive(t0).unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, low_id); + + // The lower one ignores the close for the link it never held. + for (_, frame) in closes { + low.on_frame(HIGH, LOW, frame, fresh(5), t0, 0); + } + assert_eq!(low.peer(), Some(HIGH)); + } + + #[test] + fn an_invalid_offer_is_answered_and_never_joined() { + let t0 = Instant::now(); + let good = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 1_000_000, + ttl_ms: 120_000, + }; + assert!(good.is_valid(1_000_000)); + let bad = [ + Offer { + host: "8.8.8.8".to_string(), + ..good.clone() + }, + Offer { + host: "printer.local".to_string(), + ..good.clone() + }, + Offer { + passphrase: "short".to_string(), + ..good.clone() + }, + Offer { + ssid: String::new(), + ..good.clone() + }, + Offer { + port: 0, + ..good.clone() + }, + Offer { + ttl_ms: MAX_OFFER_TTL_MS + 1, + ..good.clone() + }, + Offer { + issued_at_ms: 1_000_000 + OFFER_CLOCK_SLACK_MS + 1, + ..good.clone() + }, + Offer { + issued_at_ms: 1_000_000 - 120_000 - OFFER_CLOCK_SLACK_MS - 1, + ..good.clone() + }, + ]; + for offer in bad { + let mut iphone = machine(join_roles()); + let id = fresh(1).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer.clone())), + fresh(2), + t0, + 1_000_000, + ); + assert!(!iphone.has_directives(), "joined {offer:?}"); + let frames = iphone.take_frames(); + assert_eq!( + frames[0].1.body, + FrameBody::Close { + reason: "invalid".to_string() + }, + "{offer:?}" + ); + } + assert!(is_local_host("fe80::1")); + assert!(is_local_host("fd00::1")); + assert!(is_local_host("169.254.3.4")); + assert!(!is_local_host("2001:db8::1")); + } + + #[test] + fn frames_round_trip_and_unknown_shapes_are_refused() { + let id = fresh(1).link_id; + for body in [ + FrameBody::Request, + FrameBody::Close { + reason: "idle".to_string(), + }, + ] { + let frame = Frame::new(&id, body); + assert_eq!(Frame::parse(&frame.encode()), Some(frame)); + } + let wire = Frame::new(&id, FrameBody::Request).encode(); + assert!(wire.starts_with("{\"v\":1,\"link\":"), "{wire}"); + assert!(Frame::parse(&wire.replace("\"v\":1", "\"v\":2")).is_none()); + assert!(Frame::parse(&wire.replace(&id, "NOT-A-LINK-ID")).is_none()); + assert!( + Frame::parse(&format!("{{\"v\":1,\"link\":\"{id}\",\"kind\":\"dance\"}}")).is_none() + ); + assert!(Frame::parse(&" ".repeat(MAX_FRAME_BODY_BYTES + 1)).is_none()); + // A later field is ignored, not refused. + let later = wire.replacen('{', "{\"later\":true,", 1); + assert!(Frame::parse(&later).is_some()); + assert_eq!( + CloseReason::parse("a reason from 2030"), + CloseReason::Failed + ); + } + + #[test] + fn every_end_tells_the_platform_and_the_peer_once() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let id = android.request(HIGH, fresh(1), t0).unwrap(); + android.next_directive(t0); + assert!(android.hosting(&id, "192.168.49.1", 8988, t0, 0)); + android.take_frames(); + android.stream_proved(HIGH, t0); + android.take_changes(); + + android.stream_lost(HIGH); + let close = android.next_directive(t0).unwrap(); + assert_eq!(close.kind, FastLinkDirectiveKind::Close); + assert_eq!(close.reason, Some(CloseReason::Lost)); + assert!(android.next_directive(t0).is_none()); + let frames = android.take_frames(); + assert_eq!(frames.len(), 1); + assert_eq!( + frames[0].1.body, + FrameBody::Close { + reason: "lost".to_string() + } + ); + let changes = android.take_changes(); + assert_eq!(changes.len(), 1); + assert_eq!(changes[0].state, FastLinkState::Closed); + assert_eq!(changes[0].reason, Some(CloseReason::Lost)); + assert!(android.peer().is_none()); + } + + #[test] + fn a_close_from_the_peer_is_not_echoed() { + let t0 = Instant::now(); + let mut iphone = machine(join_roles()); + let id = iphone.request(LOW, fresh(1), t0).unwrap(); + iphone.take_frames(); + iphone.on_frame( + LOW, + HIGH, + Frame::new( + &id, + FrameBody::Close { + reason: "cannot_host".to_string(), + }, + ), + fresh(2), + t0, + 0, + ); + assert!(iphone.take_frames().is_empty()); + assert!( + !iphone.has_directives(), + "a requester's platform held nothing" + ); + let changes = iphone.take_changes(); + assert_eq!( + changes.last().unwrap().reason, + Some(CloseReason::CannotHost) + ); + } + + #[test] + fn a_platform_report_ends_the_link_without_a_directive() { + let t0 = Instant::now(); + let mut iphone = machine(join_roles()); + let id = fresh(1).link_id; + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer)), + fresh(2), + t0, + 0, + ); + iphone.next_directive(t0); + assert!(iphone.platform_ended(&id, CloseReason::Declined)); + assert!(!iphone.has_directives()); + let frames = iphone.take_frames(); + assert_eq!( + frames[0].1.body, + FrameBody::Close { + reason: "declined".to_string() + } + ); + } + + #[test] + fn timers_end_each_waiting_state() { + let t0 = Instant::now(); + + let mut host = machine(host_roles()); + host.request(HIGH, fresh(1), t0).unwrap(); + host.tick(t0 + HOSTING_TIMEOUT, |_| false); + assert_eq!( + host.take_changes().last().unwrap().reason, + Some(CloseReason::HostFailed) + ); + + let mut host = machine(host_roles()); + let id = host.request(HIGH, fresh(1), t0).unwrap(); + host.hosting(&id, "192.168.49.1", 8988, t0, 0); + host.tick(t0 + OFFER_TTL - Duration::from_secs(1), |_| false); + assert!(host.peer().is_some()); + host.tick(t0 + OFFER_TTL, |_| false); + assert_eq!( + host.take_changes().last().unwrap().reason, + Some(CloseReason::Expired) + ); + + let mut joiner = machine(join_roles()); + joiner.request(LOW, fresh(1), t0).unwrap(); + joiner.tick(t0 + REQUEST_TIMEOUT, |_| false); + assert_eq!( + joiner.take_changes().last().unwrap().reason, + Some(CloseReason::NoOffer) + ); + } + + #[test] + fn an_idle_link_ends_unless_a_transfer_holds_it() { + let t0 = Instant::now(); + let mut host = machine(host_roles()); + let id = host.request(HIGH, fresh(1), t0).unwrap(); + host.hosting(&id, "192.168.49.1", 8988, t0, 0); + host.stream_proved(HIGH, t0); + host.take_changes(); + + host.activity(HIGH, t0 + Duration::from_secs(30)); + host.tick(t0 + IDLE_LIMIT, |_| false); + assert!(host.peer().is_some(), "activity moved the idle clock"); + + host.tick(t0 + Duration::from_secs(200), |peer| peer == HIGH); + assert!(host.peer().is_some(), "a transfer in flight is not idle"); + + host.tick(t0 + Duration::from_secs(200) + IDLE_LIMIT, |_| false); + assert_eq!( + host.take_changes().last().unwrap().reason, + Some(CloseReason::Idle) + ); + } + + #[test] + fn a_repeated_request_gets_the_same_offer_again() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let id = fresh(1).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(2), + t0, + 0, + ); + android.hosting(&id, "192.168.49.1", 8988, t0, 5); + let first = android.take_frames(); + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(3), + t0, + 0, + ); + let second = android.take_frames(); + assert_eq!(first, second); + assert_eq!( + android.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Host + ); + assert!(android.next_directive(t0).is_none(), "one network, not two"); + } + + #[test] + fn a_host_address_off_the_network_is_never_offered() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let id = android.request(HIGH, fresh(1), t0).unwrap(); + android.next_directive(t0); + assert!(!android.hosting(&id, "8.8.8.8", 8988, t0, 0)); + assert!( + android.take_frames().is_empty(), + "nothing offered, and the peer knew nothing" + ); + assert_eq!( + android.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Close + ); + } +} diff --git a/crates/offline-protocol/src/lib.rs b/crates/offline-protocol/src/lib.rs index f2f11d68c..17fc6cf89 100644 --- a/crates/offline-protocol/src/lib.rs +++ b/crates/offline-protocol/src/lib.rs @@ -12,6 +12,7 @@ pub mod config; pub mod constants; pub mod error; pub mod events; +pub mod fast_link; #[cfg(feature = "file-store")] pub mod file_store; pub mod file_transfer; diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs new file mode 100644 index 000000000..2e363a204 --- /dev/null +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -0,0 +1,251 @@ +//! The engine's half of the fast link (ADR 0038). +//! +//! The state machine is [`crate::fast_link`]; this file is everything that +//! needs the engine. It checks a request may be made at all, seals each frame +//! in the 1:1 session and sends it once over the live direct link, routes a +//! decrypted frame in, feeds the machine the stream's proof, loss and +//! traffic, runs its timers on the engine's tick, turns its changes into +//! events, and wakes the platform when a directive is waiting. +//! +//! A frame is sealed with the strict encryptor and is never queued: a +//! confirmed session and a live link, or nothing (invariant 1 of +//! `docs/state-machines/fast-link.md`). + +use offline_protocol_core::time::Instant; +use offline_protocol_core::MessagePriority; +use offline_protocol_transport::TransportType; +use rand_core::{OsRng, RngCore}; +use tracing::{debug, warn}; + +use super::prefixes::internal_prefixes; +use super::OfflineProtocol; +use crate::fast_link::{ + CloseReason, FastLinkDirective, FastLinkRefusal, FastLinkRoles, Frame, FreshLink, +}; +use crate::{Error, Event, Result}; + +impl OfflineProtocol { + /// Declares what this device's platform can do. Until it does, both are + /// false and every request is refused or answered `cannot_*`. + pub fn set_fast_link_roles(&mut self, can_host: bool, can_join: bool) { + self.fast_links + .set_roles(FastLinkRoles { can_host, can_join }); + } + + /// Asks for a fast link to `peer`, and returns its id. + /// + /// Returns as soon as the first step is taken: this device starts + /// hosting when it can, and otherwise asks the peer to host. The outcome + /// arrives as `FastLinkChanged` events. Refused when the peer has not + /// advertised the capability, there is no confirmed session or no live + /// direct link to it, a peer stream already proves it, this device can + /// neither host nor join, or a link with another peer is held. + pub fn request_fast_link(&mut self, peer: &str) -> Result { + if self.is_user_blocked(peer) { + return Err(Error::UserBlocked(peer.to_string())); + } + if !self.peer_fast_link.contains(peer) { + return Err(Error::InvalidArgument(format!( + "{peer} has not advertised fast-link support" + ))); + } + if !self.confirmed_sessions.contains(peer) { + return Err(Error::InvalidState(format!( + "a fast link needs a confirmed session with {peer}" + ))); + } + self.direct_link_to(peer)?; + if self.fast_links.peer() != Some(peer) && self.peer_stream_proves(peer) { + return Err(Error::InvalidState(format!( + "a peer stream already reaches {peer}" + ))); + } + let result = self + .fast_links + .request(peer, fresh_link(), Instant::now()) + .map_err(|refusal| match refusal { + FastLinkRefusal::Unsupported => Error::InvalidState( + "this device can neither host nor join a fast link".to_string(), + ), + FastLinkRefusal::Busy => { + Error::InvalidState("a fast link with another peer is in progress".to_string()) + } + }); + self.flush_fast_link(); + result + } + + /// Ends the fast link with `peer`, if there is one. Returns whether there + /// was. + pub fn close_fast_link(&mut self, peer: &str) -> bool { + let closed = self.fast_links.close(peer); + self.flush_fast_link(); + closed + } + + /// The next instruction for the platform. Drained whenever the peer-stream + /// callback fires. + pub fn next_fast_link_directive(&mut self) -> Option { + self.fast_links.next_directive(Instant::now()) + } + + /// The host's platform brought its network up, with its listener on + /// `host:port`. The offer goes to the peer. + pub fn fast_link_hosting(&mut self, link_id: &str, host: &str, port: u16) -> Result<()> { + let accepted = self.fast_links.hosting( + link_id, + host, + port, + Instant::now(), + chrono::Utc::now().timestamp_millis(), + ); + self.flush_fast_link(); + if accepted { + Ok(()) + } else { + Err(Error::InvalidArgument(format!( + "no fast link {link_id} waiting for its network, or {host}:{port} is not a \ + private or link-local address" + ))) + } + } + + /// The platform could not do what it was told, or can no longer hold the + /// link (`reason`: `declined`, `failed`, `host_failed`, `background`, ...). + pub fn fast_link_ended(&mut self, link_id: &str, reason: &str) { + self.fast_links + .platform_ended(link_id, CloseReason::parse(reason)); + self.flush_fast_link(); + } + + /// A peer stream proved `peer`. + pub fn fast_link_stream_proved(&mut self, peer: &str) { + self.fast_links.stream_proved(peer, Instant::now()); + self.flush_fast_link(); + } + + /// The peer stream that proved `peer` ended. + pub fn fast_link_stream_lost(&mut self, peer: &str) { + self.fast_links.stream_lost(peer); + self.flush_fast_link(); + } + + /// The peer-stream slot carried a body for `peer`. + pub fn fast_link_activity(&mut self, peer: &str) { + self.fast_links.activity(peer, Instant::now()); + } + + /// A fast-link frame decrypted in the 1:1 session with `sender`, who is + /// therefore its authenticated sender. `plaintext` still carries the + /// prefix. + pub(crate) fn handle_fast_link_frame(&mut self, sender: &str, plaintext: &str) { + if self.is_user_blocked(sender) { + return; + } + let Some(body) = plaintext.strip_prefix(internal_prefixes::FAST_LINK) else { + return; + }; + let Some(frame) = Frame::parse(body) else { + debug!(sender = %sender, "Dropping a fast-link frame this version does not read"); + return; + }; + let Some(local) = self.local_address().map(str::to_string) else { + return; + }; + self.fast_links.on_frame( + sender, + &local, + frame, + fresh_link(), + Instant::now(), + chrono::Utc::now().timestamp_millis(), + ); + self.flush_fast_link(); + } + + /// The machine's timers, on the engine's tick. + pub(crate) fn tick_fast_link(&mut self) { + if self.fast_links.peer().is_none() { + return; + } + let outbound = &self.outbound_media_transfers; + self.fast_links.tick(Instant::now(), |peer| { + outbound.values().any(|transfer| transfer.recipient == peer) + }); + self.flush_fast_link(); + } + + /// Whether a peer stream holds `peer` now. + fn peer_stream_proves(&self, peer: &str) -> bool { + self.transport_manager + .get_transport(TransportType::WiFiDirect) + .is_some_and(|transport| { + transport + .connected_peers() + .iter() + .any(|link| link.peer_id == peer) + }) + } + + /// Sends what the machine queued for the peer, emits its changes, and + /// wakes the platform when a directive waits. + fn flush_fast_link(&mut self) { + for (peer, frame) in self.fast_links.take_frames() { + let content = format!("{}{}", internal_prefixes::FAST_LINK, frame.encode()); + if let Err(err) = self.send_fast_link_frame(&peer, &content) { + // Not retried: a frame that cannot leave now names a moment + // that has passed. The other side's timers end its half. + debug!(peer = %peer, error = %err, "Fast-link frame not sent"); + } + } + for change in self.fast_links.take_changes() { + self.emit_event(Event::fast_link_changed(change)); + } + if self.fast_links.has_directives() { + self.wake_peer_stream_platform(); + } + } + + /// Sealed with the strict encryptor and sent once over the live direct + /// link, with no acknowledgement, outbox or retry (ADR 0032). Fails + /// before encrypting when there is no link, so no ratchet generation is + /// spent on a frame that cannot leave. + fn send_fast_link_frame(&mut self, peer: &str, content: &str) -> Result<()> { + let transport = self.direct_link_to(peer)?; + let sealed = self.encrypt_content_for_recipient_strict(peer, content)?; + let mut message = self.create_message(peer, sealed, Some(MessagePriority::High), None)?; + message.requires_ack = false; + self.deduplicator.mark_seen_local(message.id.clone()); + if let Err(err) = self + .transport_manager + .send_via_transport(&message, transport) + { + self.transport_manager.record_retry_failure(transport); + return Err(err); + } + Ok(()) + } + + /// Wakes the platform through the peer-stream transport's callback, the + /// one it already drains bodies on. + fn wake_peer_stream_platform(&self) { + let Some(transport) = self + .transport_manager + .get_transport(TransportType::WiFiDirect) + else { + warn!("A fast-link directive waits, but there is no peer-stream transport to wake"); + return; + }; + if let Some(wifi_direct) = transport + .as_any() + .downcast_ref::() + { + wifi_direct.wake_platform(); + } + } +} + +/// A link id and credentials from the operating system's random source. +fn fresh_link() -> FreshLink { + FreshLink::generate(|buf| OsRng.fill_bytes(buf)) +} diff --git a/crates/offline-protocol/src/protocol/message_dispatch.rs b/crates/offline-protocol/src/protocol/message_dispatch.rs index b7cf4d2f9..a1dae4348 100644 --- a/crates/offline-protocol/src/protocol/message_dispatch.rs +++ b/crates/offline-protocol/src/protocol/message_dispatch.rs @@ -1678,6 +1678,9 @@ impl OfflineProtocol { if let Some(frame) = sealed_service_frame { self.handle_sealed_service_frame(&sender_owned, &frame, message); } + if let Some(frame) = fast_link_frame { + self.handle_fast_link_frame(&sender_owned, &frame); + } surfaced } DecryptResult::Empty => { diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index a468faf97..ad18e99c7 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -10,6 +10,7 @@ pub(crate) mod data; mod data_sync; mod decryption_queue; mod ephemeral; +mod fast_link; pub(crate) mod mesh_relay; mod message_dispatch; mod nostr_discovery; @@ -449,6 +450,12 @@ pub struct OfflineProtocol { /// [`FAST_LINK_V1`]: offline_protocol_sealed::FAST_LINK_V1 pub(crate) peer_fast_link: std::collections::HashSet, + /// The fast link in progress, if any, and what it has queued for the + /// peer, the platform and the application (ADR 0038). Memory only: a + /// restart ends every link, and the platform's networks with the + /// process. + pub(crate) fast_links: crate::fast_link::FastLinks, + /// Delivery ACKs waiting to be coalesced, per peer: the carrier the /// answered frames arrived on, when the first was held, and the answered /// ids with the first one's hop count. Sent as one frame once @@ -1331,6 +1338,7 @@ impl OfflineProtocol { peer_undecryptable_ack: std::collections::HashSet::new(), peer_coalesced_ack: std::collections::HashSet::new(), peer_fast_link: std::collections::HashSet::new(), + fast_links: crate::fast_link::FastLinks::default(), coalesced_acks_out: HashMap::new(), answered_deliveries: HashMap::new(), mesh_resend_generations: HashMap::new(), @@ -3888,6 +3896,7 @@ impl OfflineProtocol { #[cfg(feature = "data")] self.send_due_data_settle_offers(Instant::now()); self.tick_service_subscriptions(); + self.tick_fast_link(); self.refresh_nostr_key_package_slots(); self.refresh_nostr_discovery_claim(); // A relay is free never to send end-of-stored-events, and that is the diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index 621517f32..c608c72bf 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -4265,6 +4265,12 @@ impl OfflineProtocol { transport: Option, ) -> Result<()> { self.mark_message_sent(message, transport, Some(1)); + // Traffic on the peer-stream slot keeps a fast link off its idle + // limit (ADR 0038). Inbound traffic is noted where the platform hands + // a body up. + if transport == Some(TransportType::WiFiDirect) { + self.fast_link_activity(message.recipient.as_str()); + } // Never `?`: the frame is already on the wire, so an error here would // report a transmitted message as failed. Every transmit path asks // `defer_for_ack_capacity` first, so this is only reachable through a diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs new file mode 100644 index 000000000..62fe901f2 --- /dev/null +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -0,0 +1,272 @@ +//! The fast link through two real engines (ADR 0038): a genuine 1:1 MLS +//! session, frames sealed by one engine and decrypted by the other, carried +//! over a mock Bluetooth LE link. The state machine's own transitions are +//! tested in `crate::fast_link`; these are about what the engine adds: the +//! gates on a request, sealing, routing, events and directives. + +use std::sync::{Arc, Mutex}; + +use offline_protocol_core::Message; +use offline_protocol_transport::{MockTransport, Transport, TransportType}; + +use crate::fast_link::FastLinkDirectiveKind; +use crate::mls::InMemoryStorage; +use crate::protocol::prefixes::internal_prefixes; +use crate::protocol::tests::{create_test_config_for_user, id}; +use crate::protocol::{OfflineProtocol, SessionState, TestProtocolStateStorage}; +use crate::{Error, Event}; + +struct Node { + protocol: OfflineProtocol, + transport: MockTransport, + address: String, + events: Arc>>, +} + +impl Node { + fn new(label: &str) -> Self { + let mut config = create_test_config_for_user(label); + config.encryption.enabled = true; + let mut protocol = OfflineProtocol::new(config).expect("protocol"); + protocol + .initialize_mls( + crate::test_identity::seeded_storage(label), + Arc::new(TestProtocolStateStorage { + storage: Arc::new(InMemoryStorage::new()), + }), + ) + .expect("initialize_mls"); + let mock = MockTransport::new(TransportType::BLE); + mock.start().expect("transport start"); + let transport = mock.clone(); + protocol + .transport_manager_mut() + .add_transport(TransportType::BLE, Box::new(mock)); + let events: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink = events.clone(); + protocol.on_event(move |event| sink.lock().unwrap().push(event)); + protocol.start().expect("start"); + Self { + protocol, + transport, + address: id(label), + events, + } + } + + fn take_sent(&self) -> Vec { + let sent = self.transport.sent_messages(); + self.transport.clear_sent_messages(); + sent + } + + fn deliver(&mut self, frames: Vec) { + for frame in frames { + self.transport.queue_message(frame); + } + while self.protocol.receive_message().is_some() {} + } + + /// `(state, reason)` of every fast-link event so far, in order. + fn link_states(&self) -> Vec<(String, Option)> { + self.events + .lock() + .unwrap() + .iter() + .filter_map(|event| match event { + Event::FastLinkChanged { state, reason, .. } => { + Some((state.clone(), reason.clone())) + } + _ => None, + }) + .collect() + } +} + +/// Two engines with a confirmed session, a live Bluetooth link between them, +/// and the fast-link capability recorded on both sides. `alice` can host and +/// join, as an Android phone can; `bob` can only join, as an iPhone. +fn pair() -> (Node, Node) { + let mut alice = Node::new("alice"); + let mut bob = Node::new("bob"); + let bob_kp = { + let manager = bob.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager.get_or_create_key_package().unwrap() + }; + let welcome = { + let manager = alice.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager + .import_key_package(&bob.address, &bob_kp.key_package_data) + .unwrap(); + manager.create_session(&bob.address).unwrap() + }; + { + let manager = bob.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager.join_session(&welcome).unwrap(); + } + for (node, peer) in [(&mut alice, bob.address.clone()), (&mut bob, id("alice"))] { + node.protocol.record_encryption_capable(&peer); + node.protocol + .persist_session_state(&peer, SessionState::Confirmed, "test") + .unwrap(); + node.protocol.confirmed_sessions.insert(peer.clone()); + node.protocol.peer_fast_link.insert(peer.clone()); + node.transport.add_connected_peer(peer, -40); + } + alice.protocol.set_fast_link_roles(true, true); + bob.protocol.set_fast_link_roles(false, true); + (alice, bob) +} + +#[test] +fn an_offer_is_sealed_carried_once_and_joined() { + let (mut alice, mut bob) = pair(); + + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + let host = alice.protocol.next_fast_link_directive().unwrap(); + assert_eq!(host.kind, FastLinkDirectiveKind::Host); + assert_eq!(host.peer_id, bob.address); + let passphrase = host.passphrase.clone().unwrap(); + assert!( + alice.take_sent().is_empty(), + "nothing reaches the peer before the network is up" + ); + + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + let sent = alice.take_sent(); + assert_eq!(sent.len(), 1, "one frame, sent once"); + let offer = &sent[0]; + assert!(offer.content.starts_with(internal_prefixes::ENCRYPTED)); + assert!( + !offer.content.contains(&passphrase), + "the passphrase left in clear" + ); + assert!(!offer.requires_ack, "a fast-link frame is ephemeral"); + + bob.deliver(sent); + let join = bob.protocol.next_fast_link_directive().unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, link_id); + assert_eq!(join.peer_id, alice.address); + assert_eq!(join.ssid, host.ssid); + assert_eq!(join.passphrase.as_deref(), Some(passphrase.as_str())); + assert_eq!(join.host.as_deref(), Some("192.168.49.1")); + assert_eq!(join.port, Some(8988)); + assert!(bob.take_sent().is_empty(), "an offer is not acknowledged"); + + alice.protocol.fast_link_stream_proved(&bob.address); + bob.protocol.fast_link_stream_proved(&alice.address); + assert_eq!( + alice.link_states(), + [ + ("hosting".to_string(), None), + ("offered".to_string(), None), + ("up".to_string(), None) + ] + ); + assert_eq!( + bob.link_states(), + [("joining".to_string(), None), ("up".to_string(), None)] + ); + + // The joiner's platform loses the network: both ends close, and the + // host's platform is told to take its network down. + bob.protocol.fast_link_ended(&link_id, "background"); + alice.deliver(bob.take_sent()); + let close = alice.protocol.next_fast_link_directive().unwrap(); + assert_eq!(close.kind, FastLinkDirectiveKind::Close); + assert_eq!( + alice.link_states().last().unwrap(), + &("closed".to_string(), Some("background".to_string())) + ); + assert!(alice.take_sent().is_empty(), "a close is never echoed"); + assert!( + alice + .events + .lock() + .unwrap() + .iter() + .all(|event| !format!("{event:?}").contains(&passphrase)), + "an event carried the passphrase" + ); +} + +#[test] +fn a_joiner_asks_and_the_host_answers_under_its_id() { + let (mut alice, mut bob) = pair(); + + let link_id = bob.protocol.request_fast_link(&alice.address).unwrap(); + assert!( + bob.protocol.next_fast_link_directive().is_none(), + "a requester's platform has nothing to do yet" + ); + alice.deliver(bob.take_sent()); + + let host = alice.protocol.next_fast_link_directive().unwrap(); + assert_eq!(host.kind, FastLinkDirectiveKind::Host); + assert_eq!(host.link_id, link_id); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + bob.deliver(alice.take_sent()); + + let join = bob.protocol.next_fast_link_directive().unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, link_id); +} + +#[test] +fn a_request_is_refused_without_capability_session_or_roles() { + let (mut alice, bob) = pair(); + + alice.protocol.peer_fast_link.remove(&bob.address); + assert!(matches!( + alice.protocol.request_fast_link(&bob.address), + Err(Error::InvalidArgument(_)) + )); + alice.protocol.peer_fast_link.insert(bob.address.clone()); + + alice.protocol.confirmed_sessions.remove(&bob.address); + assert!(matches!( + alice.protocol.request_fast_link(&bob.address), + Err(Error::InvalidState(_)) + )); + alice + .protocol + .confirmed_sessions + .insert(bob.address.clone()); + + alice.protocol.set_fast_link_roles(false, false); + assert!(matches!( + alice.protocol.request_fast_link(&bob.address), + Err(Error::InvalidState(_)) + )); + + alice.transport.remove_connected_peer(&bob.address); + alice.protocol.set_fast_link_roles(true, true); + assert!( + alice.protocol.request_fast_link(&bob.address).is_err(), + "a request needs a live direct link to carry it" + ); + assert!(alice.take_sent().is_empty()); + assert!(alice.protocol.next_fast_link_directive().is_none()); +} + +#[test] +fn a_peer_that_cannot_host_says_so() { + let (mut alice, mut bob) = pair(); + alice.protocol.set_fast_link_roles(false, true); + + bob.protocol.request_fast_link(&alice.address).unwrap(); + alice.deliver(bob.take_sent()); + assert!(alice.protocol.next_fast_link_directive().is_none()); + bob.deliver(alice.take_sent()); + assert_eq!( + bob.link_states().last().unwrap(), + &("closed".to_string(), Some("cannot_host".to_string())) + ); +} diff --git a/crates/offline-protocol/src/protocol/tests/mod.rs b/crates/offline-protocol/src/protocol/tests/mod.rs index c01d52d9f..1bd3c92f7 100644 --- a/crates/offline-protocol/src/protocol/tests/mod.rs +++ b/crates/offline-protocol/src/protocol/tests/mod.rs @@ -6,6 +6,7 @@ mod data_layer; mod data_sync; mod data_sync_group; mod ephemeral; +mod fast_link; #[cfg(feature = "file-store")] mod file_stores; mod leaf_pairing; diff --git a/crates/offline-protocol/src/telemetry/record.rs b/crates/offline-protocol/src/telemetry/record.rs index b65dc8f99..c8b48493e 100644 --- a/crates/offline-protocol/src/telemetry/record.rs +++ b/crates/offline-protocol/src/telemetry/record.rs @@ -113,6 +113,7 @@ pub(crate) mod tests { "protocol.message.failed", "protocol.message.decryption_failed", "protocol.transport.switched", + "protocol.fast_link.changed", "protocol.relay.promoted", "protocol.relay.demoted", "protocol.neighbor.discovered", @@ -305,6 +306,7 @@ pub(crate) mod tests { | Event::MessageFailed { .. } | Event::MessageDecryptionFailed { .. } | Event::TransportSwitched { .. } + | Event::FastLinkChanged { .. } | Event::RelayPromoted { .. } | Event::RelayDemoted { .. } | Event::NeighborDiscovered { .. } @@ -454,6 +456,13 @@ pub(crate) mod tests { to: String::new(), reason: String::new(), }, + Event::FastLinkChanged { + peer_id: String::new(), + link_id: String::new(), + role: String::new(), + state: String::new(), + reason: None, + }, Event::RelayPromoted { connection_count: 0, battery_level: None, diff --git a/crates/offline-protocol/src/telemetry/scrub_event.rs b/crates/offline-protocol/src/telemetry/scrub_event.rs index 6c87589b0..8c0043bfa 100644 --- a/crates/offline-protocol/src/telemetry/scrub_event.rs +++ b/crates/offline-protocol/src/telemetry/scrub_event.rs @@ -304,6 +304,16 @@ fn scrub_in_place(event: &mut Event, scrubber: &Scrubber) { to: _, reason: _, } => {} + // The link id is random per link and names nobody. + Event::FastLinkChanged { + peer_id, + link_id: _, + role: _, + state: _, + reason: _, + } => { + hash_string(peer_id, scrubber); + } Event::RelayPromoted { connection_count: _, battery_level: _, @@ -941,6 +951,7 @@ fn event_variant_exhaustiveness_ward(e: &Event) { | Event::MessageFailed { .. } | Event::MessageDecryptionFailed { .. } | Event::TransportSwitched { .. } + | Event::FastLinkChanged { .. } | Event::RelayPromoted { .. } | Event::RelayDemoted { .. } | Event::NeighborDiscovered { .. } diff --git a/docs/spec/local-api.md b/docs/spec/local-api.md index d06c734c2..5cb9a3927 100644 --- a/docs/spec/local-api.md +++ b/docs/spec/local-api.md @@ -655,6 +655,7 @@ and is the one a client is written against. | `message_failed` | `message_id`, `reason`, `retry_count #` | `message_id` | | `message_decryption_failed` | `message_id`, `sender`, `code `, `reason`, `sealed_at_ms #?`, `session_established_at_ms #?` | `all` | | `transport_switched` | `from?`, `to`, `reason` | `all` | +| `fast_link_changed` | `peer_id`, `link_id`, `role`, `state`, `reason?` | `all` | | `relay_promoted` | `connection_count #`, `battery_level #?` | `all` | | `relay_demoted` | `reason` | `all` | | `neighbor_discovered` | `peer_id`, `transport`, `rssi #?` | `all` | From d8fc580a63bec1c7c3edf43928c6a18fe0b991af Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 06:04:54 +0530 Subject: [PATCH 06/81] feat(uniffi): expose the fast link across the ffi request_fast_link and close_fast_link for the application, and four calls for the peer-stream driver: declare its roles, drain directives on the callback it already drains bodies on, report its network up, and report an end. the directive record redacts its passphrase in debug. a stream's proof, loss, the layer going down and inbound bodies feed the engine's fast link. every binding, the c dispatcher and the python local api table are regenerated together, and the local api chapter classifies the new calls. --- .../sdk/FastLinkDirective.java | 159 ++++++++ ...onverterOptionalTypeFastLinkDirective.java | 32 ++ .../FfiConverterTypeFastLinkDirective.java | 49 +++ .../offlineprotocol/sdk/NamespaceLibrary.java | 18 + .../offlineprotocol/sdk/OfflineProtocol.java | 189 +++++++++ .../sdk/OfflineProtocolInterface.java | 6 + .../com/offlineprotocol/sdk/UniffiLib.java | 108 +++++ .../local_api/dispatch.py | 7 + .../offline_protocol_sdk/local_api/table.py | 24 +- .../offline_protocol_sdk/offline_protocol.py | 385 ++++++++++++++++-- .../offline_protocol/offline_protocol.kt | 277 +++++++++++++ .../ios/Generated/offline_protocol.swift | 220 ++++++++++ .../ios/Generated/offline_protocolFFI.h | 66 +++ bindings/ruby/lib/offline_protocol.rb | 291 +++++++++++++ .../src/capi/generated.rs | 80 ++++ crates/offline-protocol-uniffi/src/lib.rs | 113 +++++ .../src/offline_protocol.udl | 63 +++ docs/spec/local-api.md | 15 +- 18 files changed, 2062 insertions(+), 40 deletions(-) create mode 100644 bindings/java/src/main/java/com/offlineprotocol/sdk/FastLinkDirective.java create mode 100644 bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterOptionalTypeFastLinkDirective.java create mode 100644 bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterTypeFastLinkDirective.java diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/FastLinkDirective.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/FastLinkDirective.java new file mode 100644 index 000000000..e8cfe414f --- /dev/null +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/FastLinkDirective.java @@ -0,0 +1,159 @@ +package com.offlineprotocol.sdk; + +public class FastLinkDirective { + private java.lang.String kind; + private java.lang.String linkId; + private java.lang.String peerId; + private java.lang.String ssid; + private java.lang.String passphrase; + private java.lang.String host; + private java.lang.Short port; + private long expiresInMs; + private java.lang.String reason; + + public FastLinkDirective( + java.lang.String kind, + java.lang.String linkId, + java.lang.String peerId, + java.lang.String ssid, + java.lang.String passphrase, + java.lang.String host, + java.lang.Short port, + long expiresInMs, + java.lang.String reason + ) { + + this.kind = kind; + + this.linkId = linkId; + + this.peerId = peerId; + + this.ssid = ssid; + + this.passphrase = passphrase; + + this.host = host; + + this.port = port; + + this.expiresInMs = expiresInMs; + + this.reason = reason; + } + + public java.lang.String kind() { + return this.kind; + } + + public java.lang.String linkId() { + return this.linkId; + } + + public java.lang.String peerId() { + return this.peerId; + } + + public java.lang.String ssid() { + return this.ssid; + } + + public java.lang.String passphrase() { + return this.passphrase; + } + + public java.lang.String host() { + return this.host; + } + + public java.lang.Short port() { + return this.port; + } + + public long expiresInMs() { + return this.expiresInMs; + } + + public java.lang.String reason() { + return this.reason; + } + public void setKind(java.lang.String kind) { + this.kind = kind; + } + public void setLinkId(java.lang.String linkId) { + this.linkId = linkId; + } + public void setPeerId(java.lang.String peerId) { + this.peerId = peerId; + } + public void setSsid(java.lang.String ssid) { + this.ssid = ssid; + } + public void setPassphrase(java.lang.String passphrase) { + this.passphrase = passphrase; + } + public void setHost(java.lang.String host) { + this.host = host; + } + public void setPort(java.lang.Short port) { + this.port = port; + } + public void setExpiresInMs(long expiresInMs) { + this.expiresInMs = expiresInMs; + } + public void setReason(java.lang.String reason) { + this.reason = reason; + } + + + + + @Override + public boolean equals(java.lang.Object _uniffiOther) { + if (_uniffiOther instanceof FastLinkDirective) { + FastLinkDirective _uniffiThat = (FastLinkDirective) _uniffiOther; + return ( + java.util.Objects.equals(kind, _uniffiThat.kind) && + + java.util.Objects.equals(linkId, _uniffiThat.linkId) && + + java.util.Objects.equals(peerId, _uniffiThat.peerId) && + + java.util.Objects.equals(ssid, _uniffiThat.ssid) && + + java.util.Objects.equals(passphrase, _uniffiThat.passphrase) && + + java.util.Objects.equals(host, _uniffiThat.host) && + + java.util.Objects.equals(port, _uniffiThat.port) && + + expiresInMs == _uniffiThat.expiresInMs && + + java.util.Objects.equals(reason, _uniffiThat.reason) + + ); + }; + return false; + } + @Override + public int hashCode() { + int _uniffiHash = 17; + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(kind); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(linkId); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(peerId); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(ssid); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(passphrase); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(host); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(port); + _uniffiHash = 31 * _uniffiHash + java.lang.Long.hashCode(expiresInMs); + _uniffiHash = 31 * _uniffiHash + java.util.Objects.hashCode(reason); + return _uniffiHash; + } + + + + + +} + + diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterOptionalTypeFastLinkDirective.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterOptionalTypeFastLinkDirective.java new file mode 100644 index 000000000..d6e93b677 --- /dev/null +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterOptionalTypeFastLinkDirective.java @@ -0,0 +1,32 @@ +package com.offlineprotocol.sdk; + +public enum FfiConverterOptionalTypeFastLinkDirective implements FfiConverterRustBuffer { + INSTANCE; + + @Override + public FastLinkDirective read(java.nio.ByteBuffer buf) { + if (buf.get() == (byte)0) { + return null; + } + return FfiConverterTypeFastLinkDirective.INSTANCE.read(buf); + } + + @Override + public long allocationSize(FastLinkDirective value) { + if (value == null) { + return 1L; + } else { + return 1L + FfiConverterTypeFastLinkDirective.INSTANCE.allocationSize(value); + } + } + + @Override + public void write(FastLinkDirective value, java.nio.ByteBuffer buf) { + if (value == null) { + buf.put((byte)0); + } else { + buf.put((byte)1); + FfiConverterTypeFastLinkDirective.INSTANCE.write(value, buf); + } + } +} diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterTypeFastLinkDirective.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterTypeFastLinkDirective.java new file mode 100644 index 000000000..e696b56e2 --- /dev/null +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/FfiConverterTypeFastLinkDirective.java @@ -0,0 +1,49 @@ +package com.offlineprotocol.sdk; + + +public enum FfiConverterTypeFastLinkDirective implements FfiConverterRustBuffer { + INSTANCE; + + @Override + public FastLinkDirective read(java.nio.ByteBuffer buf) { + return new FastLinkDirective( + FfiConverterString.INSTANCE.read(buf), + FfiConverterString.INSTANCE.read(buf), + FfiConverterString.INSTANCE.read(buf), + FfiConverterOptionalString.INSTANCE.read(buf), + FfiConverterOptionalString.INSTANCE.read(buf), + FfiConverterOptionalString.INSTANCE.read(buf), + FfiConverterOptionalShort.INSTANCE.read(buf), + FfiConverterLong.INSTANCE.read(buf), + FfiConverterOptionalString.INSTANCE.read(buf) + ); + } + + @Override + public long allocationSize(FastLinkDirective value) { + return ( + FfiConverterString.INSTANCE.allocationSize(value.kind()) + + FfiConverterString.INSTANCE.allocationSize(value.linkId()) + + FfiConverterString.INSTANCE.allocationSize(value.peerId()) + + FfiConverterOptionalString.INSTANCE.allocationSize(value.ssid()) + + FfiConverterOptionalString.INSTANCE.allocationSize(value.passphrase()) + + FfiConverterOptionalString.INSTANCE.allocationSize(value.host()) + + FfiConverterOptionalShort.INSTANCE.allocationSize(value.port()) + + FfiConverterLong.INSTANCE.allocationSize(value.expiresInMs()) + + FfiConverterOptionalString.INSTANCE.allocationSize(value.reason()) + ); + } + + @Override + public void write(FastLinkDirective value, java.nio.ByteBuffer buf) { + FfiConverterString.INSTANCE.write(value.kind(), buf); + FfiConverterString.INSTANCE.write(value.linkId(), buf); + FfiConverterString.INSTANCE.write(value.peerId(), buf); + FfiConverterOptionalString.INSTANCE.write(value.ssid(), buf); + FfiConverterOptionalString.INSTANCE.write(value.passphrase(), buf); + FfiConverterOptionalString.INSTANCE.write(value.host(), buf); + FfiConverterOptionalShort.INSTANCE.write(value.port(), buf); + FfiConverterLong.INSTANCE.write(value.expiresInMs(), buf); + FfiConverterOptionalString.INSTANCE.write(value.reason(), buf); + } +} diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java index 19d127945..a9bdabaa7 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java @@ -235,6 +235,9 @@ static void uniffiCheckApiChecksums() { if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer() != ((short) 44634)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link() != ((short) 32622)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores() != ((short) 57369)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } @@ -562,6 +565,9 @@ static void uniffiCheckApiChecksums() { if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group() != ((short) 36114)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link() != ((short) 19701)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration() != ((short) 3982)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } @@ -718,18 +724,30 @@ static void uniffiCheckApiChecksums() { if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes() != ((short) 24438)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended() != ((short) 54290)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting() != ((short) 47337)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message() != ((short) 50868)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received() != ((short) 59107)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive() != ((short) 7498)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected() != ((short) 38596)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != ((short) 15986)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != ((short) 20631)) { + throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); + } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != ((short) 12337)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java index b150f04b2..3bf3ed695 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java @@ -690,6 +690,37 @@ public void cancelFileTransfer(java.lang.String fileId) throws ProtocolException + @Override + public boolean closeFastLink(java.lang.String peerId) { + try { + return FfiConverterBoolean.INSTANCE.lift( + callWithHandle(_uniffiHandle -> { + try { + + return + UniffiHelpers.uniffiRustCall( (_allocator, _status) -> { + return UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link(_uniffiHandle, + FfiConverterString.INSTANCE.lower(peerId), _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ); + } catch (java.lang.RuntimeException _uniffi_ex) { + + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + @Override public void closeFileStores() throws ProtocolException { try { @@ -4194,6 +4225,40 @@ public void renameGroup(java.lang.String groupId, java.lang.String newName) thro + @Override + public java.lang.String requestFastLink(java.lang.String peerId) throws ProtocolException { + try { + return FfiConverterString.INSTANCE.lift( + callWithHandle(_uniffiHandle -> { + try { + + return + UniffiHelpers.uniffiRustCallWithError(new ProtocolExceptionErrorHandler(), (_allocator, _status) -> { + return UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link(_allocator, _uniffiHandle, + FfiConverterString.INSTANCE.lower(peerId), _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ); + } catch (java.lang.RuntimeException _uniffi_ex) { + + if (ProtocolException.class.isInstance(_uniffi_ex.getCause())) { + throw (ProtocolException)_uniffi_ex.getCause(); + } + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + @Override public boolean requestGroupRelayRegistration(java.lang.String groupId) throws ProtocolException { try { @@ -5878,6 +5943,69 @@ public boolean verifySignatureBytes(byte[] publicKey, byte[] data, byte[] signat + @Override + public void wifiDirectFastLinkEnded(java.lang.String linkId, java.lang.String reason) { + try { + + callWithHandle(_uniffiHandle -> { + try { + + UniffiHelpers.uniffiRustCall( (_allocator, _status) -> { + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended(_uniffiHandle, + FfiConverterString.INSTANCE.lower(linkId), FfiConverterString.INSTANCE.lower(reason), _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ; + } catch (java.lang.RuntimeException _uniffi_ex) { + + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + + @Override + public void wifiDirectFastLinkHosting(java.lang.String linkId, java.lang.String host, short port) throws ProtocolException { + try { + + callWithHandle(_uniffiHandle -> { + try { + + UniffiHelpers.uniffiRustCallWithError(new ProtocolExceptionErrorHandler(), (_allocator, _status) -> { + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting(_uniffiHandle, + FfiConverterString.INSTANCE.lower(linkId), FfiConverterString.INSTANCE.lower(host), port, _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ; + } catch (java.lang.RuntimeException _uniffi_ex) { + + if (ProtocolException.class.isInstance(_uniffi_ex.getCause())) { + throw (ProtocolException)_uniffi_ex.getCause(); + } + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + @Override public WifiDirectMessage wifiDirectGetNextMessage() { try { @@ -5942,6 +6070,37 @@ public void wifiDirectMessageReceived(java.lang.String senderId, java.util.List< + @Override + public FastLinkDirective wifiDirectNextFastLinkDirective() { + try { + return FfiConverterOptionalTypeFastLinkDirective.INSTANCE.lift( + callWithHandle(_uniffiHandle -> { + try { + + return + UniffiHelpers.uniffiRustCall( (_allocator, _status) -> { + return UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive(_allocator, _uniffiHandle, + _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ); + } catch (java.lang.RuntimeException _uniffi_ex) { + + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + @Override public void wifiDirectPeerConnected(java.lang.String peerId) throws ProtocolException { try { @@ -6008,6 +6167,36 @@ public void wifiDirectPeerDisconnected(java.lang.String peerId) throws ProtocolE + @Override + public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin) { + try { + + callWithHandle(_uniffiHandle -> { + try { + + UniffiHelpers.uniffiRustCall( (_allocator, _status) -> { + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(_uniffiHandle, + FfiConverterBoolean.INSTANCE.lower(canHost), FfiConverterBoolean.INSTANCE.lower(canJoin), _status); + }); + } catch (java.lang.RuntimeException _uniffi_ex) { + throw _uniffi_ex; + } catch (java.lang.Exception _uniffi_ex) { + throw new java.lang.RuntimeException(_uniffi_ex); + } + }) + ; + } catch (java.lang.RuntimeException _uniffi_ex) { + + + if (InternalException.class.isInstance(_uniffi_ex.getCause())) { + throw (InternalException)_uniffi_ex.getCause(); + } + throw _uniffi_ex; + } + } + + + @Override public void wifiDirectStatusChanged(boolean isConnected) throws ProtocolException { try { diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java index 69721e285..8f21e55b0 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java @@ -19,6 +19,7 @@ public interface OfflineProtocolInterface { public void blockUser(java.lang.String userId) throws ProtocolException; public java.lang.String cancelConnectionRequest(java.lang.String recipient) throws ProtocolException; public void cancelFileTransfer(java.lang.String fileId) throws ProtocolException; + public boolean closeFastLink(java.lang.String peerId); public void closeFileStores() throws ProtocolException; public MlsGroupInfo createGroup(java.lang.String groupName) throws ProtocolException; public java.lang.String createInvite(java.lang.String petname, boolean sign) throws ProtocolException; @@ -128,6 +129,7 @@ public interface OfflineProtocolInterface { public void removeFromGroup(java.lang.String groupId, java.lang.String memberId) throws ProtocolException; public void removeTransport(TransportType transportType) throws ProtocolException; public void renameGroup(java.lang.String groupId, java.lang.String newName) throws ProtocolException; + public java.lang.String requestFastLink(java.lang.String peerId) throws ProtocolException; public boolean requestGroupRelayRegistration(java.lang.String groupId) throws ProtocolException; public boolean resolveUsername(java.lang.String username) throws ProtocolException; public void resume() throws ProtocolException; @@ -180,10 +182,14 @@ public interface OfflineProtocolInterface { public void updateTransportMetrics(TransportType transportType, TransportMetrics metrics) throws ProtocolException; public boolean verifySignature(java.util.List publicKey, java.util.List data, java.util.List signature) throws ProtocolException; public boolean verifySignatureBytes(byte[] publicKey, byte[] data, byte[] signature) throws ProtocolException; + public void wifiDirectFastLinkEnded(java.lang.String linkId, java.lang.String reason); + public void wifiDirectFastLinkHosting(java.lang.String linkId, java.lang.String host, short port) throws ProtocolException; public WifiDirectMessage wifiDirectGetNextMessage(); public void wifiDirectMessageReceived(java.lang.String senderId, java.util.List data) throws ProtocolException; + public FastLinkDirective wifiDirectNextFastLinkDirective(); public void wifiDirectPeerConnected(java.lang.String peerId) throws ProtocolException; public void wifiDirectPeerDisconnected(java.lang.String peerId) throws ProtocolException; + public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin); public void wifiDirectStatusChanged(boolean isConnected) throws ProtocolException; } diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java index dc81951fc..ac54b9b3a 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java @@ -686,6 +686,15 @@ static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_file } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); + + static byte uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link(long ptr, java.lang.foreign.MemorySegment peerId, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + return (byte) MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link.invokeExact(ptr, peerId, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.ADDRESS)); @@ -1667,6 +1676,15 @@ static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_rename_grou } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link", java.lang.foreign.FunctionDescriptor.of(RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); + + static java.lang.foreign.MemorySegment uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link(java.lang.foreign.SegmentAllocator _allocator, long ptr, java.lang.foreign.MemorySegment peerId, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + return (java.lang.foreign.MemorySegment) MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link.invokeExact(_allocator, ptr, peerId, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); @@ -2135,6 +2153,24 @@ static byte uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_sign } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); + + static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended(long ptr, java.lang.foreign.MemorySegment linkId, java.lang.foreign.MemorySegment reason, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended.invokeExact(ptr, linkId, reason, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.JAVA_SHORT, java.lang.foreign.ValueLayout.ADDRESS)); + + static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting(long ptr, java.lang.foreign.MemorySegment linkId, java.lang.foreign.MemorySegment host, short port, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting.invokeExact(ptr, linkId, host, port, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message", java.lang.foreign.FunctionDescriptor.of(RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.ADDRESS)); @@ -2153,6 +2189,15 @@ static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive", java.lang.foreign.FunctionDescriptor.of(RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.ADDRESS)); + + static java.lang.foreign.MemorySegment uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive(java.lang.foreign.SegmentAllocator _allocator, long ptr, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + return (java.lang.foreign.MemorySegment) MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive.invokeExact(_allocator, ptr, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, RustBuffer.LAYOUT, java.lang.foreign.ValueLayout.ADDRESS)); @@ -2171,6 +2216,15 @@ static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.ADDRESS)); + + static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(long ptr, byte canHost, byte canJoin, java.lang.foreign.MemorySegment _uniffiOutErr) { + try { + MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.invokeExact(ptr, canHost, canJoin, _uniffiOutErr); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.ADDRESS)); @@ -3359,6 +3413,15 @@ static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_canc } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); @@ -4340,6 +4403,15 @@ static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rena } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); @@ -4808,6 +4880,24 @@ static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_veri } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); @@ -4826,6 +4916,15 @@ static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); @@ -4844,6 +4943,15 @@ static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); + + static short uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() { + try { + return (short) MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles.invokeExact(); + } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } + } + // uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed = findDowncallHandle("uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed", java.lang.foreign.FunctionDescriptor.of(java.lang.foreign.ValueLayout.JAVA_SHORT)); diff --git a/bindings/python/offline_protocol_sdk/local_api/dispatch.py b/bindings/python/offline_protocol_sdk/local_api/dispatch.py index ada8d7f43..4f602c9cf 100644 --- a/bindings/python/offline_protocol_sdk/local_api/dispatch.py +++ b/bindings/python/offline_protocol_sdk/local_api/dispatch.py @@ -102,6 +102,9 @@ "unblock_user", "get_blocked_users", "is_user_blocked", + # fast link + "request_fast_link", + "close_fast_link", # transports and metrics "get_active_transports", "get_transport_metrics", @@ -257,6 +260,10 @@ "wifi_direct_get_next_message", "wifi_direct_peer_connected", "wifi_direct_peer_disconnected", + "wifi_direct_set_fast_link_roles", + "wifi_direct_next_fast_link_directive", + "wifi_direct_fast_link_hosting", + "wifi_direct_fast_link_ended", # gateway client "reticulum_status_changed", "reticulum_message_received", diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index 612705b60..56a2f4254 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799" +UDL_SHA256 = "7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', @@ -249,6 +249,7 @@ 'cancel_connection_request': ((('recipient', 'string'),), 'string'), 'cancel_file_transfer': ((('file_id', 'string'),), 'void'), + 'close_fast_link': ((('peer_id', 'string'),), 'boolean'), 'close_file_stores': ((), 'void'), 'constructor': ((('config', 'ProtocolConfig'),), 'object'), 'create_group': ((('group_name', 'string'),), 'MlsGroupInfo'), @@ -436,6 +437,7 @@ 'void'), 'rename_group': ((('group_id', 'string'), ('new_name', 'string')), 'void'), + 'request_fast_link': ((('peer_id', 'string'),), 'string'), 'request_group_relay_registration': ((('group_id', 'string'),), 'boolean'), 'resolve_username': ((('username', 'string'),), 'boolean'), @@ -559,13 +561,24 @@ ('data', 'bytes'), ('signature', 'bytes')), 'boolean'), + 'wifi_direct_fast_link_ended': ((('link_id', 'string'), + ('reason', 'string')), + 'void'), + 'wifi_direct_fast_link_hosting': ((('link_id', 'string'), + ('host', 'string'), + ('port', 'u16')), + 'void'), 'wifi_direct_get_next_message': ((), 'WifiDirectMessage?'), 'wifi_direct_message_received': ((('sender_id', 'string'), ('data', 'sequence')), 'void'), + 'wifi_direct_next_fast_link_directive': ((), 'FastLinkDirective?'), 'wifi_direct_peer_connected': ((('peer_id', 'string'),), 'void'), 'wifi_direct_peer_disconnected': ((('peer_id', 'string'),), 'void'), + 'wifi_direct_set_fast_link_roles': ((('can_host', 'boolean'), + ('can_join', 'boolean')), + 'void'), 'wifi_direct_status_changed': ((('is_connected', 'boolean'),), 'void')}, 'namespace': {'derive_address': ((('public_key', 'sequence'),), 'string'), @@ -638,6 +651,15 @@ ('store_pending', 'boolean', False), ('require_encryption', 'boolean', True), ('pending_queue', 'PendingQueueConfig', False)), + 'FastLinkDirective': (('kind', 'string', False), + ('link_id', 'string', False), + ('peer_id', 'string', False), + ('ssid', 'string?', False), + ('passphrase', 'string?', False), + ('host', 'string?', False), + ('port', 'u16?', False), + ('expires_in_ms', 'u64', False), + ('reason', 'string?', False)), 'FileProgress': (('file_id', 'string', False), ('chunks_sent', 'u32', False), ('total_chunks', 'u32', False), diff --git a/bindings/python/offline_protocol_sdk/offline_protocol.py b/bindings/python/offline_protocol_sdk/offline_protocol.py index d21174ac7..b77bdca73 100644 --- a/bindings/python/offline_protocol_sdk/offline_protocol.py +++ b/bindings/python/offline_protocol_sdk/offline_protocol.py @@ -697,6 +697,8 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer() != 44634: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link() != 32622: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores() != 57369: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_create_group() != 13199: @@ -915,6 +917,8 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group() != 36114: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link() != 19701: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration() != 3982: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_resolve_username() != 56081: @@ -1019,14 +1023,22 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes() != 24438: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended() != 54290: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting() != 47337: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message() != 50868: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received() != 59107: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive() != 7498: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected() != 38596: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != 15986: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 20631: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != 12337: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_constructor_offlineprotocol_new() != 30125: @@ -1273,6 +1285,9 @@ def _uniffi_check_api_checksums(lib): _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores.restype = ctypes.c_uint16 @@ -1600,6 +1615,9 @@ def _uniffi_check_api_checksums(lib): _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration.restype = ctypes.c_uint16 @@ -1756,18 +1774,30 @@ def _uniffi_check_api_checksums(lib): _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected.restype = ctypes.c_uint16 +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles.argtypes = ( +) +_UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles.restype = ctypes.c_uint16 _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed.argtypes = ( ) _UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed.restype = ctypes.c_uint16 @@ -2263,6 +2293,12 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_file_transfer.restype = None +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link.argtypes = ( + ctypes.c_uint64, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link.restype = ctypes.c_int8 _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores.argtypes = ( ctypes.c_uint64, ctypes.POINTER(_UniffiRustCallStatus), @@ -2902,6 +2938,12 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_rename_group.restype = None +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link.argtypes = ( + ctypes.c_uint64, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link.restype = _UniffiRustBuffer _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration.argtypes = ( ctypes.c_uint64, _UniffiRustBuffer, @@ -3245,6 +3287,21 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_signature_bytes.restype = ctypes.c_int8 +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended.argtypes = ( + ctypes.c_uint64, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended.restype = None +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting.argtypes = ( + ctypes.c_uint64, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.c_uint16, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting.restype = None _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message.argtypes = ( ctypes.c_uint64, ctypes.POINTER(_UniffiRustCallStatus), @@ -3257,6 +3314,11 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_message_received.restype = None +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive.restype = _UniffiRustBuffer _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected.argtypes = ( ctypes.c_uint64, _UniffiRustBuffer, @@ -3269,6 +3331,13 @@ def _uniffi_check_api_checksums(lib): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected.restype = None +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.argtypes = ( + ctypes.c_uint64, + ctypes.c_int8, + ctypes.c_int8, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.restype = None _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed.argtypes = ( ctypes.c_uint64, ctypes.c_int8, @@ -4365,6 +4434,147 @@ def write(value, buf): _UniffiFfiConverterBoolean.write(value.require_encryption, buf) _UniffiFfiConverterTypePendingQueueConfig.write(value.pending_queue, buf) +class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiFfiConverterString.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiFfiConverterString.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiFfiConverterString.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + +class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt): + CLASS_NAME = "u16" + VALUE_MIN = 0 + VALUE_MAX = 2**16 + + @staticmethod + def read(buf): + return buf.read_u16() + + @staticmethod + def write(value, buf): + buf.write_u16(value) + +class _UniffiFfiConverterOptionalUInt16(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiFfiConverterUInt16.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiFfiConverterUInt16.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiFfiConverterUInt16.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + +@dataclass +class FastLinkDirective: + def __init__(self, *, kind:str, link_id:str, peer_id:str, ssid:typing.Optional[str], passphrase:typing.Optional[str], host:typing.Optional[str], port:typing.Optional[int], expires_in_ms:int, reason:typing.Optional[str]): + self.kind = kind + self.link_id = link_id + self.peer_id = peer_id + self.ssid = ssid + self.passphrase = passphrase + self.host = host + self.port = port + self.expires_in_ms = expires_in_ms + self.reason = reason + + + + + def __str__(self): + return "FastLinkDirective(kind={}, link_id={}, peer_id={}, ssid={}, passphrase={}, host={}, port={}, expires_in_ms={}, reason={})".format(self.kind, self.link_id, self.peer_id, self.ssid, self.passphrase, self.host, self.port, self.expires_in_ms, self.reason) + def __eq__(self, other): + if self.kind != other.kind: + return False + if self.link_id != other.link_id: + return False + if self.peer_id != other.peer_id: + return False + if self.ssid != other.ssid: + return False + if self.passphrase != other.passphrase: + return False + if self.host != other.host: + return False + if self.port != other.port: + return False + if self.expires_in_ms != other.expires_in_ms: + return False + if self.reason != other.reason: + return False + return True + +class _UniffiFfiConverterTypeFastLinkDirective(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + return FastLinkDirective( + kind=_UniffiFfiConverterString.read(buf), + link_id=_UniffiFfiConverterString.read(buf), + peer_id=_UniffiFfiConverterString.read(buf), + ssid=_UniffiFfiConverterOptionalString.read(buf), + passphrase=_UniffiFfiConverterOptionalString.read(buf), + host=_UniffiFfiConverterOptionalString.read(buf), + port=_UniffiFfiConverterOptionalUInt16.read(buf), + expires_in_ms=_UniffiFfiConverterUInt64.read(buf), + reason=_UniffiFfiConverterOptionalString.read(buf), + ) + + @staticmethod + def check_lower(value): + _UniffiFfiConverterString.check_lower(value.kind) + _UniffiFfiConverterString.check_lower(value.link_id) + _UniffiFfiConverterString.check_lower(value.peer_id) + _UniffiFfiConverterOptionalString.check_lower(value.ssid) + _UniffiFfiConverterOptionalString.check_lower(value.passphrase) + _UniffiFfiConverterOptionalString.check_lower(value.host) + _UniffiFfiConverterOptionalUInt16.check_lower(value.port) + _UniffiFfiConverterUInt64.check_lower(value.expires_in_ms) + _UniffiFfiConverterOptionalString.check_lower(value.reason) + + @staticmethod + def write(value, buf): + _UniffiFfiConverterString.write(value.kind, buf) + _UniffiFfiConverterString.write(value.link_id, buf) + _UniffiFfiConverterString.write(value.peer_id, buf) + _UniffiFfiConverterOptionalString.write(value.ssid, buf) + _UniffiFfiConverterOptionalString.write(value.passphrase, buf) + _UniffiFfiConverterOptionalString.write(value.host, buf) + _UniffiFfiConverterOptionalUInt16.write(value.port, buf) + _UniffiFfiConverterUInt64.write(value.expires_in_ms, buf) + _UniffiFfiConverterOptionalString.write(value.reason, buf) + @dataclass class FileProgress: def __init__(self, *, file_id:str, chunks_sent:int, total_chunks:int, percentage:int): @@ -4575,31 +4785,6 @@ def write(value, buf): _UniffiFfiConverterBoolean.write(value.ready, buf) _UniffiFfiConverterSequenceString.write(value.unknown_members, buf) -class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer): - @classmethod - def check_lower(cls, value): - if value is not None: - _UniffiFfiConverterString.check_lower(value) - - @classmethod - def write(cls, value, buf): - if value is None: - buf.write_u8(0) - return - - buf.write_u8(1) - _UniffiFfiConverterString.write(value, buf) - - @classmethod - def read(cls, buf): - flag = buf.read_u8() - if flag == 0: - return None - elif flag == 1: - return _UniffiFfiConverterString.read(buf) - else: - raise InternalError("Unexpected flag byte for optional type") - @dataclass class InternetMessage: def __init__(self, *, message_id:str, recipient_id:str, data:typing.List[int], reply_to_msg:typing.Optional[str], control_op:typing.Optional[str], control_payload:typing.Optional[str]): @@ -7645,19 +7830,6 @@ def write(value, buf): -class _UniffiFfiConverterUInt16(_UniffiConverterPrimitiveInt): - CLASS_NAME = "u16" - VALUE_MIN = 0 - VALUE_MAX = 2**16 - - @staticmethod - def read(buf): - return buf.read_u16() - - @staticmethod - def write(value, buf): - buf.write_u16(value) - @@ -10999,6 +11171,31 @@ def read(cls, buf): else: raise InternalError("Unexpected flag byte for optional type") +class _UniffiFfiConverterOptionalTypeFastLinkDirective(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiFfiConverterTypeFastLinkDirective.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiFfiConverterTypeFastLinkDirective.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiFfiConverterTypeFastLinkDirective.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + class OfflineProtocolProtocol(typing.Protocol): @@ -11038,6 +11235,8 @@ def cancel_connection_request(self, recipient: str) -> str: raise NotImplementedError def cancel_file_transfer(self, file_id: str) -> None: raise NotImplementedError + def close_fast_link(self, peer_id: str) -> bool: + raise NotImplementedError def close_file_stores(self, ) -> None: raise NotImplementedError def create_group(self, group_name: str) -> MlsGroupInfo: @@ -11256,6 +11455,8 @@ def remove_transport(self, transport_type: TransportType) -> None: raise NotImplementedError def rename_group(self, group_id: str,new_name: str) -> None: raise NotImplementedError + def request_fast_link(self, peer_id: str) -> str: + raise NotImplementedError def request_group_relay_registration(self, group_id: str) -> bool: raise NotImplementedError def resolve_username(self, username: str) -> bool: @@ -11360,14 +11561,22 @@ def verify_signature(self, public_key: typing.List[int],data: typing.List[int],s raise NotImplementedError def verify_signature_bytes(self, public_key: bytes,data: bytes,signature: bytes) -> bool: raise NotImplementedError + def wifi_direct_fast_link_ended(self, link_id: str,reason: str) -> None: + raise NotImplementedError + def wifi_direct_fast_link_hosting(self, link_id: str,host: str,port: int) -> None: + raise NotImplementedError def wifi_direct_get_next_message(self, ) -> typing.Optional[WifiDirectMessage]: raise NotImplementedError def wifi_direct_message_received(self, sender_id: str,data: typing.List[int]) -> None: raise NotImplementedError + def wifi_direct_next_fast_link_directive(self, ) -> typing.Optional[FastLinkDirective]: + raise NotImplementedError def wifi_direct_peer_connected(self, peer_id: str) -> None: raise NotImplementedError def wifi_direct_peer_disconnected(self, peer_id: str) -> None: raise NotImplementedError + def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool) -> None: + raise NotImplementedError def wifi_direct_status_changed(self, is_connected: bool) -> None: raise NotImplementedError @@ -11676,6 +11885,21 @@ def cancel_file_transfer(self, file_id: str) -> None: *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) + def close_fast_link(self, peer_id: str) -> bool: + + _UniffiFfiConverterString.check_lower(peer_id) + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + _UniffiFfiConverterString.lower(peer_id), + ) + _uniffi_lift_return = _UniffiFfiConverterBoolean.lift + _uniffi_error_converter = None + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def close_file_stores(self, ) -> None: _uniffi_lowered_args = ( self._uniffi_clone_handle(), @@ -13266,6 +13490,21 @@ def rename_group(self, group_id: str,new_name: str) -> None: *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) + def request_fast_link(self, peer_id: str) -> str: + + _UniffiFfiConverterString.check_lower(peer_id) + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + _UniffiFfiConverterString.lower(peer_id), + ) + _uniffi_lift_return = _UniffiFfiConverterString.lift + _uniffi_error_converter = _UniffiFfiConverterTypeProtocolError + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def request_group_relay_registration(self, group_id: str) -> bool: _UniffiFfiConverterString.check_lower(group_id) @@ -14139,6 +14378,45 @@ def verify_signature_bytes(self, public_key: bytes,data: bytes,signature: bytes) *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) + def wifi_direct_fast_link_ended(self, link_id: str,reason: str) -> None: + + _UniffiFfiConverterString.check_lower(link_id) + + _UniffiFfiConverterString.check_lower(reason) + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + _UniffiFfiConverterString.lower(link_id), + _UniffiFfiConverterString.lower(reason), + ) + _uniffi_lift_return = lambda val: None + _uniffi_error_converter = None + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) + def wifi_direct_fast_link_hosting(self, link_id: str,host: str,port: int) -> None: + + _UniffiFfiConverterString.check_lower(link_id) + + _UniffiFfiConverterString.check_lower(host) + + _UniffiFfiConverterUInt16.check_lower(port) + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + _UniffiFfiConverterString.lower(link_id), + _UniffiFfiConverterString.lower(host), + _UniffiFfiConverterUInt16.lower(port), + ) + _uniffi_lift_return = lambda val: None + _uniffi_error_converter = _UniffiFfiConverterTypeProtocolError + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def wifi_direct_get_next_message(self, ) -> typing.Optional[WifiDirectMessage]: _uniffi_lowered_args = ( self._uniffi_clone_handle(), @@ -14169,6 +14447,18 @@ def wifi_direct_message_received(self, sender_id: str,data: typing.List[int]) -> *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) + def wifi_direct_next_fast_link_directive(self, ) -> typing.Optional[FastLinkDirective]: + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + ) + _uniffi_lift_return = _UniffiFfiConverterOptionalTypeFastLinkDirective.lift + _uniffi_error_converter = None + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def wifi_direct_peer_connected(self, peer_id: str) -> None: _UniffiFfiConverterString.check_lower(peer_id) @@ -14199,6 +14489,24 @@ def wifi_direct_peer_disconnected(self, peer_id: str) -> None: *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) + def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool) -> None: + + _UniffiFfiConverterBoolean.check_lower(can_host) + + _UniffiFfiConverterBoolean.check_lower(can_join) + _uniffi_lowered_args = ( + self._uniffi_clone_handle(), + _UniffiFfiConverterBoolean.lower(can_host), + _UniffiFfiConverterBoolean.lower(can_join), + ) + _uniffi_lift_return = lambda val: None + _uniffi_error_converter = None + _uniffi_ffi_result = _uniffi_rust_call_with_error( + _uniffi_error_converter, + _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles, + *_uniffi_lowered_args, + ) + return _uniffi_lift_return(_uniffi_ffi_result) def wifi_direct_status_changed(self, is_connected: bool) -> None: _UniffiFfiConverterBoolean.check_lower(is_connected) @@ -14329,6 +14637,7 @@ def verify_identity_assertion(assertion: typing.List[int]) -> str: "DorsConfig", "PendingQueueConfig", "EncryptionConfig", + "FastLinkDirective", "FileProgress", "ForwardInfo", "GatewayAddressDeclaration", diff --git a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt index aaaaac5fe..a81f6abc1 100644 --- a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt +++ b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt @@ -1001,6 +1001,8 @@ internal object IntegrityCheckingUniffiLib { ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores( ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_create_group( @@ -1219,6 +1221,8 @@ internal object IntegrityCheckingUniffiLib { ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration( ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_resolve_username( @@ -1323,14 +1327,22 @@ internal object IntegrityCheckingUniffiLib { ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended( + ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message( ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected( ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected( ): Int + external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles( + ): Int external fun uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed( ): Int external fun uniffi_offline_protocol_uniffi_checksum_constructor_datastore_new( @@ -1542,6 +1554,8 @@ internal object UniffiLib { ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_file_transfer(`ptr`: Long,`fileId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link(`ptr`: Long,`peerId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, + ): Byte external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus, ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_create_group(`ptr`: Long,`groupName`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, @@ -1760,6 +1774,8 @@ internal object UniffiLib { ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_rename_group(`ptr`: Long,`groupId`: RustBuffer.ByValue,`newName`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link(`ptr`: Long,`peerId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, + ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration(`ptr`: Long,`groupId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Byte external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_resolve_username(`ptr`: Long,`username`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, @@ -1864,14 +1880,22 @@ internal object UniffiLib { ): Byte external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_signature_bytes(`ptr`: Long,`publicKey`: RustBuffer.ByValue,`data`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Byte + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended(`ptr`: Long,`linkId`: RustBuffer.ByValue,`reason`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, + ): Unit + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting(`ptr`: Long,`linkId`: RustBuffer.ByValue,`host`: RustBuffer.ByValue,`port`: Short,uniffi_out_err: UniffiRustCallStatus, + ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus, ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_message_received(`ptr`: Long,`senderId`: RustBuffer.ByValue,`data`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus, + ): RustBuffer.ByValue external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected(`ptr`: Long,`peerId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected(`ptr`: Long,`peerId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(`ptr`: Long,`canHost`: Byte,`canJoin`: Byte,uniffi_out_err: UniffiRustCallStatus, + ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed(`ptr`: Long,`isConnected`: Byte,uniffi_out_err: UniffiRustCallStatus, ): Unit external fun uniffi_offline_protocol_uniffi_fn_init_callback_vtable_bletransportcallback(`vtable`: UniffiVTableCallbackInterfaceBleTransportCallback, @@ -2219,6 +2243,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) { if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer() and 0xFFFF) != 44634) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link() and 0xFFFF) != 32622) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores() and 0xFFFF) != 57369) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } @@ -2546,6 +2573,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) { if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group() and 0xFFFF) != 36114) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link() and 0xFFFF) != 19701) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration() and 0xFFFF) != 3982) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } @@ -2702,18 +2732,30 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) { if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes() and 0xFFFF) != 24438) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended() and 0xFFFF) != 54290) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting() and 0xFFFF) != 47337) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message() and 0xFFFF) != 50868) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received() and 0xFFFF) != 59107) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive() and 0xFFFF) != 7498) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected() and 0xFFFF) != 38596) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() and 0xFFFF) != 15986) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() and 0xFFFF) != 20631) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() and 0xFFFF) != 12337) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } @@ -4714,6 +4756,8 @@ public interface OfflineProtocolInterface { fun `cancelFileTransfer`(`fileId`: kotlin.String) + fun `closeFastLink`(`peerId`: kotlin.String): kotlin.Boolean + fun `closeFileStores`() fun `createGroup`(`groupName`: kotlin.String): MlsGroupInfo @@ -4932,6 +4976,8 @@ public interface OfflineProtocolInterface { fun `renameGroup`(`groupId`: kotlin.String, `newName`: kotlin.String) + fun `requestFastLink`(`peerId`: kotlin.String): kotlin.String + fun `requestGroupRelayRegistration`(`groupId`: kotlin.String): kotlin.Boolean fun `resolveUsername`(`username`: kotlin.String): kotlin.Boolean @@ -5036,14 +5082,22 @@ public interface OfflineProtocolInterface { fun `verifySignatureBytes`(`publicKey`: kotlin.ByteArray, `data`: kotlin.ByteArray, `signature`: kotlin.ByteArray): kotlin.Boolean + fun `wifiDirectFastLinkEnded`(`linkId`: kotlin.String, `reason`: kotlin.String) + + fun `wifiDirectFastLinkHosting`(`linkId`: kotlin.String, `host`: kotlin.String, `port`: kotlin.UShort) + fun `wifiDirectGetNextMessage`(): WifiDirectMessage? fun `wifiDirectMessageReceived`(`senderId`: kotlin.String, `data`: List) + fun `wifiDirectNextFastLinkDirective`(): FastLinkDirective? + fun `wifiDirectPeerConnected`(`peerId`: kotlin.String) fun `wifiDirectPeerDisconnected`(`peerId`: kotlin.String) + fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean) + fun `wifiDirectStatusChanged`(`isConnected`: kotlin.Boolean) companion object @@ -5411,6 +5465,20 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface + override fun `closeFastLink`(`peerId`: kotlin.String): kotlin.Boolean { + return FfiConverterBoolean.lift( + callWithHandle { + uniffiRustCall() { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link( + it, + + FfiConverterString.lower(`peerId`),_status) +} + } + ) + } + + @Throws(ProtocolException::class)override fun `closeFileStores`() = @@ -6936,6 +7004,21 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface + @Throws(ProtocolException::class)override fun `requestFastLink`(`peerId`: kotlin.String): kotlin.String { + return FfiConverterString.lift( + callWithHandle { + uniffiRustCallWithError(ProtocolException) { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link( + it, + + FfiConverterString.lower(`peerId`),_status) +} + } + ) + } + + + @Throws(ProtocolException::class)override fun `requestGroupRelayRegistration`(`groupId`: kotlin.String): kotlin.Boolean { return FfiConverterBoolean.lift( callWithHandle { @@ -7698,6 +7781,36 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface } + override fun `wifiDirectFastLinkEnded`(`linkId`: kotlin.String, `reason`: kotlin.String) + = + callWithHandle { + uniffiRustCall() { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended( + it, + + FfiConverterString.lower(`linkId`), + FfiConverterString.lower(`reason`),_status) +} + } + + + + + @Throws(ProtocolException::class)override fun `wifiDirectFastLinkHosting`(`linkId`: kotlin.String, `host`: kotlin.String, `port`: kotlin.UShort) + = + callWithHandle { + uniffiRustCallWithError(ProtocolException) { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting( + it, + + FfiConverterString.lower(`linkId`), + FfiConverterString.lower(`host`), + FfiConverterUShort.lower(`port`),_status) +} + } + + + override fun `wifiDirectGetNextMessage`(): WifiDirectMessage? { return FfiConverterOptionalTypeWifiDirectMessage.lift( callWithHandle { @@ -7726,6 +7839,19 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface + override fun `wifiDirectNextFastLinkDirective`(): FastLinkDirective? { + return FfiConverterOptionalTypeFastLinkDirective.lift( + callWithHandle { + uniffiRustCall() { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive( + it, + _status) +} + } + ) + } + + @Throws(ProtocolException::class)override fun `wifiDirectPeerConnected`(`peerId`: kotlin.String) = @@ -7754,6 +7880,20 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface + override fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean) + = + callWithHandle { + uniffiRustCall() { _status -> + UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles( + it, + + FfiConverterBoolean.lower(`canHost`), + FfiConverterBoolean.lower(`canJoin`),_status) +} + } + + + @Throws(ProtocolException::class)override fun `wifiDirectStatusChanged`(`isConnected`: kotlin.Boolean) = @@ -8352,6 +8492,79 @@ public object FfiConverterTypeEncryptionConfig: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): FastLinkDirective { + return FastLinkDirective( + FfiConverterString.read(buf), + FfiConverterString.read(buf), + FfiConverterString.read(buf), + FfiConverterOptionalString.read(buf), + FfiConverterOptionalString.read(buf), + FfiConverterOptionalString.read(buf), + FfiConverterOptionalUShort.read(buf), + FfiConverterULong.read(buf), + FfiConverterOptionalString.read(buf), + ) + } + + override fun allocationSize(value: FastLinkDirective) = ( + FfiConverterString.allocationSize(value.`kind`) + + FfiConverterString.allocationSize(value.`linkId`) + + FfiConverterString.allocationSize(value.`peerId`) + + FfiConverterOptionalString.allocationSize(value.`ssid`) + + FfiConverterOptionalString.allocationSize(value.`passphrase`) + + FfiConverterOptionalString.allocationSize(value.`host`) + + FfiConverterOptionalUShort.allocationSize(value.`port`) + + FfiConverterULong.allocationSize(value.`expiresInMs`) + + FfiConverterOptionalString.allocationSize(value.`reason`) + ) + + override fun write(value: FastLinkDirective, buf: ByteBuffer) { + FfiConverterString.write(value.`kind`, buf) + FfiConverterString.write(value.`linkId`, buf) + FfiConverterString.write(value.`peerId`, buf) + FfiConverterOptionalString.write(value.`ssid`, buf) + FfiConverterOptionalString.write(value.`passphrase`, buf) + FfiConverterOptionalString.write(value.`host`, buf) + FfiConverterOptionalUShort.write(value.`port`, buf) + FfiConverterULong.write(value.`expiresInMs`, buf) + FfiConverterOptionalString.write(value.`reason`, buf) + } +} + + + data class FileProgress ( var `fileId`: kotlin.String , @@ -12388,6 +12601,38 @@ public object FfiConverterOptionalUByte: FfiConverterRustBuffer { +/** + * @suppress + */ +public object FfiConverterOptionalUShort: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): kotlin.UShort? { + if (buf.get().toInt() == 0) { + return null + } + return FfiConverterUShort.read(buf) + } + + override fun allocationSize(value: kotlin.UShort?): ULong { + if (value == null) { + return 1UL + } else { + return 1UL + FfiConverterUShort.allocationSize(value) + } + } + + override fun write(value: kotlin.UShort?, buf: ByteBuffer) { + if (value == null) { + buf.put(0) + } else { + buf.put(1) + FfiConverterUShort.write(value, buf) + } + } +} + + + + /** * @suppress */ @@ -12708,6 +12953,38 @@ public object FfiConverterOptionalTypeCustodyConfig: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): FastLinkDirective? { + if (buf.get().toInt() == 0) { + return null + } + return FfiConverterTypeFastLinkDirective.read(buf) + } + + override fun allocationSize(value: FastLinkDirective?): ULong { + if (value == null) { + return 1UL + } else { + return 1UL + FfiConverterTypeFastLinkDirective.allocationSize(value) + } + } + + override fun write(value: FastLinkDirective?, buf: ByteBuffer) { + if (value == null) { + buf.put(0) + } else { + buf.put(1) + FfiConverterTypeFastLinkDirective.write(value, buf) + } + } +} + + + + /** * @suppress */ diff --git a/bindings/react-native/ios/Generated/offline_protocol.swift b/bindings/react-native/ios/Generated/offline_protocol.swift index 65ad61aad..e661149be 100644 --- a/bindings/react-native/ios/Generated/offline_protocol.swift +++ b/bindings/react-native/ios/Generated/offline_protocol.swift @@ -1559,6 +1559,8 @@ public protocol OfflineProtocolProtocol: AnyObject, Sendable { func cancelFileTransfer(fileId: String) throws + func closeFastLink(peerId: String) -> Bool + func closeFileStores() throws func createGroup(groupName: String) throws -> MlsGroupInfo @@ -1777,6 +1779,8 @@ public protocol OfflineProtocolProtocol: AnyObject, Sendable { func renameGroup(groupId: String, newName: String) throws + func requestFastLink(peerId: String) throws -> String + func requestGroupRelayRegistration(groupId: String) throws -> Bool func resolveUsername(username: String) throws -> Bool @@ -1881,14 +1885,22 @@ public protocol OfflineProtocolProtocol: AnyObject, Sendable { func verifySignatureBytes(publicKey: Data, data: Data, signature: Data) throws -> Bool + func wifiDirectFastLinkEnded(linkId: String, reason: String) + + func wifiDirectFastLinkHosting(linkId: String, host: String, port: UInt16) throws + func wifiDirectGetNextMessage() -> WifiDirectMessage? func wifiDirectMessageReceived(senderId: String, data: [UInt8]) throws + func wifiDirectNextFastLinkDirective() -> FastLinkDirective? + func wifiDirectPeerConnected(peerId: String) throws func wifiDirectPeerDisconnected(peerId: String) throws + func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool) + func wifiDirectStatusChanged(isConnected: Bool) throws } @@ -2124,6 +2136,16 @@ open func cancelFileTransfer(fileId: String)throws {try rustCallWithError(FfiC } } +open func closeFastLink(peerId: String) -> Bool { + return try! FfiConverterBool.lift(try! rustCall() { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link( + self.uniffiCloneHandle(), + FfiConverterString.lower(peerId),uniffiCallStatus + ) +}) +} + open func closeFileStores()throws {try rustCallWithError(FfiConverterTypeProtocolError_lift) { uniffiCallStatus in uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores( @@ -3156,6 +3178,16 @@ open func renameGroup(groupId: String, newName: String)throws {try rustCallWit } } +open func requestFastLink(peerId: String)throws -> String { + return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypeProtocolError_lift) { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link( + self.uniffiCloneHandle(), + FfiConverterString.lower(peerId),uniffiCallStatus + ) +}) +} + open func requestGroupRelayRegistration(groupId: String)throws -> Bool { return try FfiConverterBool.lift(try rustCallWithError(FfiConverterTypeProtocolError_lift) { uniffiCallStatus in @@ -3677,6 +3709,27 @@ open func verifySignatureBytes(publicKey: Data, data: Data, signature: Data)thro }) } +open func wifiDirectFastLinkEnded(linkId: String, reason: String) {try! rustCall() { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended( + self.uniffiCloneHandle(), + FfiConverterString.lower(linkId), + FfiConverterString.lower(reason),uniffiCallStatus + ) +} +} + +open func wifiDirectFastLinkHosting(linkId: String, host: String, port: UInt16)throws {try rustCallWithError(FfiConverterTypeProtocolError_lift) { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting( + self.uniffiCloneHandle(), + FfiConverterString.lower(linkId), + FfiConverterString.lower(host), + FfiConverterUInt16.lower(port),uniffiCallStatus + ) +} +} + open func wifiDirectGetNextMessage() -> WifiDirectMessage? { return try! FfiConverterOptionTypeWifiDirectMessage.lift(try! rustCall() { uniffiCallStatus in @@ -3696,6 +3749,15 @@ open func wifiDirectMessageReceived(senderId: String, data: [UInt8])throws {tr } } +open func wifiDirectNextFastLinkDirective() -> FastLinkDirective? { + return try! FfiConverterOptionTypeFastLinkDirective.lift(try! rustCall() { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive( + self.uniffiCloneHandle(),uniffiCallStatus + ) +}) +} + open func wifiDirectPeerConnected(peerId: String)throws {try rustCallWithError(FfiConverterTypeProtocolError_lift) { uniffiCallStatus in uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected( @@ -3714,6 +3776,16 @@ open func wifiDirectPeerDisconnected(peerId: String)throws {try rustCallWithEr } } +open func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool) {try! rustCall() { + uniffiCallStatus in + uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles( + self.uniffiCloneHandle(), + FfiConverterBool.lower(canHost), + FfiConverterBool.lower(canJoin),uniffiCallStatus + ) +} +} + open func wifiDirectStatusChanged(isConnected: Bool)throws {try rustCallWithError(FfiConverterTypeProtocolError_lift) { uniffiCallStatus in uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed( @@ -4395,6 +4467,88 @@ public func FfiConverterTypeEncryptionConfig_lower(_ value: EncryptionConfig) -> } +public struct FastLinkDirective: Equatable, Hashable { + public var kind: String + public var linkId: String + public var peerId: String + public var ssid: String? + public var passphrase: String? + public var host: String? + public var port: UInt16? + public var expiresInMs: UInt64 + public var reason: String? + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(kind: String, linkId: String, peerId: String, ssid: String?, passphrase: String?, host: String?, port: UInt16?, expiresInMs: UInt64, reason: String?) { + self.kind = kind + self.linkId = linkId + self.peerId = peerId + self.ssid = ssid + self.passphrase = passphrase + self.host = host + self.port = port + self.expiresInMs = expiresInMs + self.reason = reason + } + + + + +} + +#if compiler(>=6) +extension FastLinkDirective: Sendable {} +#endif + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeFastLinkDirective: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FastLinkDirective { + return + try FastLinkDirective( + kind: FfiConverterString.read(from: &buf), + linkId: FfiConverterString.read(from: &buf), + peerId: FfiConverterString.read(from: &buf), + ssid: FfiConverterOptionString.read(from: &buf), + passphrase: FfiConverterOptionString.read(from: &buf), + host: FfiConverterOptionString.read(from: &buf), + port: FfiConverterOptionUInt16.read(from: &buf), + expiresInMs: FfiConverterUInt64.read(from: &buf), + reason: FfiConverterOptionString.read(from: &buf) + ) + } + + public static func write(_ value: FastLinkDirective, into buf: inout [UInt8]) { + FfiConverterString.write(value.kind, into: &buf) + FfiConverterString.write(value.linkId, into: &buf) + FfiConverterString.write(value.peerId, into: &buf) + FfiConverterOptionString.write(value.ssid, into: &buf) + FfiConverterOptionString.write(value.passphrase, into: &buf) + FfiConverterOptionString.write(value.host, into: &buf) + FfiConverterOptionUInt16.write(value.port, into: &buf) + FfiConverterUInt64.write(value.expiresInMs, into: &buf) + FfiConverterOptionString.write(value.reason, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeFastLinkDirective_lift(_ buf: RustBuffer) throws -> FastLinkDirective { + return try FfiConverterTypeFastLinkDirective.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeFastLinkDirective_lower(_ value: FastLinkDirective) -> RustBuffer { + return FfiConverterTypeFastLinkDirective.lower(value) +} + + public struct FileProgress: Equatable, Hashable { public var fileId: String public var chunksSent: UInt32 @@ -10200,6 +10354,30 @@ fileprivate struct FfiConverterOptionUInt8: FfiConverterRustBuffer { } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterOptionUInt16: FfiConverterRustBuffer { + typealias SwiftType = UInt16? + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + guard let value = value else { + writeInt(&buf, Int8(0)) + return + } + writeInt(&buf, Int8(1)) + FfiConverterUInt16.write(value, into: &buf) + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { + switch try readInt(&buf) as Int8 { + case 0: return nil + case 1: return try FfiConverterUInt16.read(from: &buf) + default: throw UniffiInternalError.unexpectedOptionalTag + } + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -10440,6 +10618,30 @@ fileprivate struct FfiConverterOptionTypeCustodyConfig: FfiConverterRustBuffer { } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterOptionTypeFastLinkDirective: FfiConverterRustBuffer { + typealias SwiftType = FastLinkDirective? + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + guard let value = value else { + writeInt(&buf, Int8(0)) + return + } + writeInt(&buf, Int8(1)) + FfiConverterTypeFastLinkDirective.write(value, into: &buf) + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { + switch try readInt(&buf) as Int8 { + case 0: return nil + case 1: return try FfiConverterTypeFastLinkDirective.read(from: &buf) + default: throw UniffiInternalError.unexpectedOptionalTag + } + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -11373,6 +11575,9 @@ private let initializationResult: InitializationResult = { if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer() != 44634) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link() != 32622) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores() != 57369) { return InitializationResult.apiChecksumMismatch } @@ -11700,6 +11905,9 @@ private let initializationResult: InitializationResult = { if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group() != 36114) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link() != 19701) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration() != 3982) { return InitializationResult.apiChecksumMismatch } @@ -11856,18 +12064,30 @@ private let initializationResult: InitializationResult = { if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes() != 24438) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended() != 54290) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting() != 47337) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message() != 50868) { return InitializationResult.apiChecksumMismatch } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received() != 59107) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive() != 7498) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected() != 38596) { return InitializationResult.apiChecksumMismatch } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != 15986) { return InitializationResult.apiChecksumMismatch } + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 20631) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != 12337) { return InitializationResult.apiChecksumMismatch } diff --git a/bindings/react-native/ios/Generated/offline_protocolFFI.h b/bindings/react-native/ios/Generated/offline_protocolFFI.h index 1365e730c..750727149 100644 --- a/bindings/react-native/ios/Generated/offline_protocolFFI.h +++ b/bindings/react-native/ios/Generated/offline_protocolFFI.h @@ -773,6 +773,11 @@ RustBuffer uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_conne void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_file_transfer(uint64_t ptr, RustBuffer file_id, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_CLOSE_FAST_LINK +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_CLOSE_FAST_LINK +int8_t uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link(uint64_t ptr, RustBuffer peer_id, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_CLOSE_FILE_STORES #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_CLOSE_FILE_STORES void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores(uint64_t ptr, RustCallStatus *_Nonnull out_status @@ -1318,6 +1323,11 @@ void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_remove_transport(u void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_rename_group(uint64_t ptr, RustBuffer group_id, RustBuffer new_name, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_REQUEST_FAST_LINK +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_REQUEST_FAST_LINK +RustBuffer uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link(uint64_t ptr, RustBuffer peer_id, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_REQUEST_GROUP_RELAY_REGISTRATION #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_REQUEST_GROUP_RELAY_REGISTRATION int8_t uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration(uint64_t ptr, RustBuffer group_id, RustCallStatus *_Nonnull out_status @@ -1578,6 +1588,16 @@ int8_t uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_signature int8_t uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_signature_bytes(uint64_t ptr, RustBuffer public_key, RustBuffer data, RustBuffer signature, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_ENDED +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_ENDED +void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended(uint64_t ptr, RustBuffer link_id, RustBuffer reason, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_HOSTING +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_HOSTING +void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting(uint64_t ptr, RustBuffer link_id, RustBuffer host, uint16_t port, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_GET_NEXT_MESSAGE #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_GET_NEXT_MESSAGE RustBuffer uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message(uint64_t ptr, RustCallStatus *_Nonnull out_status @@ -1588,6 +1608,11 @@ RustBuffer uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_ void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_message_received(uint64_t ptr, RustBuffer sender_id, RustBuffer data, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_NEXT_FAST_LINK_DIRECTIVE +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_NEXT_FAST_LINK_DIRECTIVE +RustBuffer uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive(uint64_t ptr, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_PEER_CONNECTED #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_PEER_CONNECTED void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected(uint64_t ptr, RustBuffer peer_id, RustCallStatus *_Nonnull out_status @@ -1598,6 +1623,11 @@ void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_c void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected(uint64_t ptr, RustBuffer peer_id, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES +void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(uint64_t ptr, int8_t can_host, int8_t can_join, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_STATUS_CHANGED #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_STATUS_CHANGED void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed(uint64_t ptr, int8_t is_connected, RustCallStatus *_Nonnull out_status @@ -2324,6 +2354,12 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_c #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_CANCEL_FILE_TRANSFER uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_cancel_file_transfer(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_CLOSE_FAST_LINK +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_CLOSE_FAST_LINK +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_CLOSE_FILE_STORES @@ -2978,6 +3014,12 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_remove_t #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_RENAME_GROUP uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_rename_group(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_REQUEST_FAST_LINK +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_REQUEST_FAST_LINK +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_REQUEST_GROUP_RELAY_REGISTRATION @@ -3290,6 +3332,18 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_s #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_VERIFY_SIGNATURE_BYTES uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_verify_signature_bytes(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_ENDED +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_ENDED +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_HOSTING +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_FAST_LINK_HOSTING +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_GET_NEXT_MESSAGE @@ -3302,6 +3356,12 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_dir #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_MESSAGE_RECEIVED uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_message_received(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_NEXT_FAST_LINK_DIRECTIVE +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_NEXT_FAST_LINK_DIRECTIVE +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_PEER_CONNECTED @@ -3314,6 +3374,12 @@ uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_dir #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_PEER_DISCONNECTED uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES +#define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES +uint16_t uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_CHECKSUM_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_STATUS_CHANGED diff --git a/bindings/ruby/lib/offline_protocol.rb b/bindings/ruby/lib/offline_protocol.rb index 248665528..19407bc05 100644 --- a/bindings/ruby/lib/offline_protocol.rb +++ b/bindings/ruby/lib/offline_protocol.rb @@ -439,6 +439,33 @@ def consume_into_TypeEncryptionConfig end end + # The Record type FastLinkDirective. + + def self.check_lower_TypeFastLinkDirective(v) + + + + RustBuffer.check_lower_Optionalstring(v.ssid) + RustBuffer.check_lower_Optionalstring(v.passphrase) + RustBuffer.check_lower_Optionalstring(v.host) + RustBuffer.check_lower_Optionalu16(v.port) + + RustBuffer.check_lower_Optionalstring(v.reason) + end + + def self.alloc_from_TypeFastLinkDirective(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_TypeFastLinkDirective(v) + return builder.finalize + end + end + + def consume_into_TypeFastLinkDirective + consumeWithStream do |stream| + return stream.read_TypeFastLinkDirective + end + end + # The Record type FileProgress. def self.check_lower_TypeFileProgress(v) @@ -1824,6 +1851,27 @@ def consume_into_Optionalu8 end end + # The Optional type for u16. + + def self.check_lower_Optionalu16(v) + if !v.nil? + + end + end + + def self.alloc_from_Optionalu16(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_Optionalu16(v) + return builder.finalize() + end + end + + def consume_into_Optionalu16 + consumeWithStream do |stream| + return stream.read_Optionalu16 + end + end + # The Optional type for i16. def self.check_lower_Optionali16(v) @@ -2034,6 +2082,27 @@ def consume_into_OptionalTypeCustodyConfig end end + # The Optional type for TypeFastLinkDirective. + + def self.check_lower_OptionalTypeFastLinkDirective(v) + if !v.nil? + RustBuffer.check_lower_TypeFastLinkDirective(v) + end + end + + def self.alloc_from_OptionalTypeFastLinkDirective(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_OptionalTypeFastLinkDirective(v) + return builder.finalize() + end + end + + def consume_into_OptionalTypeFastLinkDirective + consumeWithStream do |stream| + return stream.read_OptionalTypeFastLinkDirective + end + end + # The Optional type for TypeFileProgress. def self.check_lower_OptionalTypeFileProgress(v) @@ -2866,6 +2935,22 @@ def read_TypeEncryptionConfig ) end + # The Record type FastLinkDirective. + + def read_TypeFastLinkDirective + FastLinkDirective.new( + kind: read_string, + link_id: read_string, + peer_id: read_string, + ssid: read_Optionalstring, + passphrase: read_Optionalstring, + host: read_Optionalstring, + port: read_Optionalu16, + expires_in_ms: read_u64, + reason: read_Optionalstring + ) + end + # The Record type FileProgress. def read_TypeFileProgress @@ -4050,6 +4135,21 @@ def read_Optionalu8 end + # The Optional type for u16. + + def read_Optionalu16 + flag = unpack_from 1, 'c' + + if flag == 0 + return nil + elsif flag == 1 + return read_u16 + else + raise InternalError, 'Unexpected flag byte for Optionalu16' + end + end + + # The Optional type for i16. def read_Optionali16 @@ -4200,6 +4300,21 @@ def read_OptionalTypeCustodyConfig end + # The Optional type for TypeFastLinkDirective. + + def read_OptionalTypeFastLinkDirective + flag = unpack_from 1, 'c' + + if flag == 0 + return nil + elsif flag == 1 + return read_TypeFastLinkDirective + else + raise InternalError, 'Unexpected flag byte for OptionalTypeFastLinkDirective' + end + end + + # The Optional type for TypeFileProgress. def read_OptionalTypeFileProgress @@ -4852,6 +4967,20 @@ def write_TypeEncryptionConfig(v) self.write_TypePendingQueueConfig(v.pending_queue) end + # The Record type FastLinkDirective. + + def write_TypeFastLinkDirective(v) + self.write_string(v.kind) + self.write_string(v.link_id) + self.write_string(v.peer_id) + self.write_Optionalstring(v.ssid) + self.write_Optionalstring(v.passphrase) + self.write_Optionalstring(v.host) + self.write_Optionalu16(v.port) + self.write_u64(v.expires_in_ms) + self.write_Optionalstring(v.reason) + end + # The Record type FileProgress. def write_TypeFileProgress(v) @@ -5791,6 +5920,17 @@ def write_Optionalu8(v) end end + # The Optional type for u16. + + def write_Optionalu16(v) + if v.nil? + pack_into(1, 'c', 0) + else + pack_into(1, 'c', 1) + self.write_u16(v) + end + end + # The Optional type for i16. def write_Optionali16(v) @@ -5901,6 +6041,17 @@ def write_OptionalTypeCustodyConfig(v) end end + # The Optional type for TypeFastLinkDirective. + + def write_OptionalTypeFastLinkDirective(v) + if v.nil? + pack_into(1, 'c', 0) + else + pack_into(1, 'c', 1) + self.write_TypeFastLinkDirective(v) + end + end + # The Optional type for TypeFileProgress. def write_OptionalTypeFileProgress(v) @@ -6945,6 +7096,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link, + [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], + :int8 + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores, [:uint64, RustCallStatus.by_ref], :void @@ -7381,6 +7536,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link, + [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_group_relay_registration, [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], :int8 @@ -7589,6 +7748,14 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], :int8 + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended, + [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], + :void + + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting, + [:uint64, RustBuffer.by_value, RustBuffer.by_value, :uint16, RustCallStatus.by_ref], + :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message, [:uint64, RustCallStatus.by_ref], RustBuffer.by_value @@ -7597,6 +7764,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive, + [:uint64, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_connected, [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], :void @@ -7605,6 +7776,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [:uint64, RustBuffer.by_value, RustCallStatus.by_ref], :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles, + [:uint64, :int8, :int8, RustCallStatus.by_ref], + :void + attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed, [:uint64, :int8, RustCallStatus.by_ref], :void @@ -8133,6 +8308,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_fast_link, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_close_file_stores, [], :uint16 @@ -8569,6 +8748,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_fast_link, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_request_group_relay_registration, [], :uint16 @@ -8777,6 +8960,14 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_ended, + [], + :uint16 + + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_fast_link_hosting, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_get_next_message, [], :uint16 @@ -8785,6 +8976,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_next_fast_link_directive, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_connected, [], :uint16 @@ -8793,6 +8988,10 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct [], :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles, + [], + :uint16 + attach_function :uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed, [], :uint16 @@ -9467,6 +9666,56 @@ def ==(other) true end +end + + # Record type FastLinkDirective +class FastLinkDirective + attr_reader :kind, :link_id, :peer_id, :ssid, :passphrase, :host, :port, :expires_in_ms, :reason + + def initialize(kind:, link_id:, peer_id:, ssid:, passphrase:, host:, port:, expires_in_ms:, reason:) + @kind = kind + @link_id = link_id + @peer_id = peer_id + @ssid = ssid + @passphrase = passphrase + @host = host + @port = port + @expires_in_ms = expires_in_ms + @reason = reason + end + + def ==(other) + if @kind != other.kind + return false + end + if @link_id != other.link_id + return false + end + if @peer_id != other.peer_id + return false + end + if @ssid != other.ssid + return false + end + if @passphrase != other.passphrase + return false + end + if @host != other.host + return false + end + if @port != other.port + return false + end + if @expires_in_ms != other.expires_in_ms + return false + end + if @reason != other.reason + return false + end + + true + end + end # Record type FileProgress @@ -11959,6 +12208,12 @@ def cancel_file_transfer(file_id) ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_cancel_file_transfer,uniffi_clone_handle(),RustBuffer.alloc_from_string(file_id)) end + def close_fast_link(peer_id) + peer_id = ::OfflineProtocol::uniffi_utf8(peer_id) + + result = ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_fast_link,uniffi_clone_handle(),RustBuffer.alloc_from_string(peer_id)) + return 1 == result + end def close_file_stores() ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_close_file_stores,uniffi_clone_handle(),) end @@ -12583,6 +12838,12 @@ def rename_group(group_id, new_name) ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_rename_group,uniffi_clone_handle(),RustBuffer.alloc_from_string(group_id),RustBuffer.alloc_from_string(new_name)) end + def request_fast_link(peer_id) + peer_id = ::OfflineProtocol::uniffi_utf8(peer_id) + + result = ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_request_fast_link,uniffi_clone_handle(),RustBuffer.alloc_from_string(peer_id)) + return result.consume_into_string + end def request_group_relay_registration(group_id) group_id = ::OfflineProtocol::uniffi_utf8(group_id) @@ -12957,6 +13218,24 @@ def verify_signature_bytes(public_key, data, signature) result = ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_verify_signature_bytes,uniffi_clone_handle(),RustBuffer.alloc_from_bytes(public_key),RustBuffer.alloc_from_bytes(data),RustBuffer.alloc_from_bytes(signature)) return 1 == result end + def wifi_direct_fast_link_ended(link_id, reason) + link_id = ::OfflineProtocol::uniffi_utf8(link_id) + + reason = ::OfflineProtocol::uniffi_utf8(reason) + + ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_ended,uniffi_clone_handle(),RustBuffer.alloc_from_string(link_id),RustBuffer.alloc_from_string(reason)) + end + + def wifi_direct_fast_link_hosting(link_id, host, port) + link_id = ::OfflineProtocol::uniffi_utf8(link_id) + + host = ::OfflineProtocol::uniffi_utf8(host) + + port = ::OfflineProtocol::uniffi_in_range(port, "u16", 0, 2**16) + + ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_fast_link_hosting,uniffi_clone_handle(),RustBuffer.alloc_from_string(link_id),RustBuffer.alloc_from_string(host),port) + end + def wifi_direct_get_next_message() result = ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_get_next_message,uniffi_clone_handle(),) return result.consume_into_OptionalTypeWifiDirectMessage @@ -12969,6 +13248,10 @@ def wifi_direct_message_received(sender_id, data) ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_message_received,uniffi_clone_handle(),RustBuffer.alloc_from_string(sender_id),RustBuffer.alloc_from_Sequenceu8(data)) end + def wifi_direct_next_fast_link_directive() + result = ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_next_fast_link_directive,uniffi_clone_handle(),) + return result.consume_into_OptionalTypeFastLinkDirective + end def wifi_direct_peer_connected(peer_id) peer_id = ::OfflineProtocol::uniffi_utf8(peer_id) @@ -12981,6 +13264,14 @@ def wifi_direct_peer_disconnected(peer_id) ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected,uniffi_clone_handle(),RustBuffer.alloc_from_string(peer_id)) end + def wifi_direct_set_fast_link_roles(can_host, can_join) + can_host = can_host ? true : false + + can_join = can_join ? true : false + + ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles,uniffi_clone_handle(),(can_host ? 1 : 0),(can_join ? 1 : 0)) + end + def wifi_direct_status_changed(is_connected) is_connected = is_connected ? true : false diff --git a/crates/offline-protocol-uniffi/src/capi/generated.rs b/crates/offline-protocol-uniffi/src/capi/generated.rs index 46971573f..bca3f107e 100644 --- a/crates/offline-protocol-uniffi/src/capi/generated.rs +++ b/crates/offline-protocol-uniffi/src/capi/generated.rs @@ -2188,6 +2188,47 @@ impl Codec for Vec { } } +impl Codec for crate::FastLinkDirective { + fn decode(value: &Value, at: &str) -> Decoded { + let mut f = Fields::new(value, at, "FastLinkDirective")?; + let out = Self { + kind: f.take("kind")?, + link_id: f.take("link_id")?, + peer_id: f.take("peer_id")?, + ssid: f.take("ssid")?, + passphrase: f.take("passphrase")?, + host: f.take("host")?, + port: f.take("port")?, + expires_in_ms: f.take("expires_in_ms")?, + reason: f.take("reason")?, + }; + f.finish()?; + Ok(out) + } + fn encode(&self) -> Value { + object(vec![ + ("kind", self.kind.encode()), + ("link_id", self.link_id.encode()), + ("peer_id", self.peer_id.encode()), + ("ssid", self.ssid.encode()), + ("passphrase", self.passphrase.encode()), + ("host", self.host.encode()), + ("port", self.port.encode()), + ("expires_in_ms", self.expires_in_ms.encode()), + ("reason", self.reason.encode()), + ]) + } +} + +impl Codec for Vec { + fn decode(value: &Value, at: &str) -> Decoded { + decode_array(value, at) + } + fn encode(&self) -> Value { + encode_array(self) + } +} + impl Codec for crate::GatewayAddressDeclaration { fn decode(value: &Value, at: &str) -> Decoded { let mut f = Fields::new(value, at, "GatewayAddressDeclaration")?; @@ -2653,6 +2694,18 @@ pub fn call_engine(target: &crate::OfflineProtocol, method: &str, mut args: Fiel target.internet_address_declaration_refused(arg_reason); Ok(Value::Null) } + "request_fast_link" => { + let arg_peer_id = args.take("peer_id")?; + args.finish()?; + let result = target.request_fast_link(arg_peer_id)?; + Ok(result.encode()) + } + "close_fast_link" => { + let arg_peer_id = args.take("peer_id")?; + args.finish()?; + let result = target.close_fast_link(arg_peer_id); + Ok(result.encode()) + } "wifi_direct_status_changed" => { let arg_is_connected = args.take("is_connected")?; args.finish()?; @@ -2683,6 +2736,33 @@ pub fn call_engine(target: &crate::OfflineProtocol, method: &str, mut args: Fiel target.wifi_direct_peer_disconnected(arg_peer_id)?; Ok(Value::Null) } + "wifi_direct_set_fast_link_roles" => { + let arg_can_host = args.take("can_host")?; + let arg_can_join = args.take("can_join")?; + args.finish()?; + target.wifi_direct_set_fast_link_roles(arg_can_host, arg_can_join); + Ok(Value::Null) + } + "wifi_direct_next_fast_link_directive" => { + args.finish()?; + let result = target.wifi_direct_next_fast_link_directive(); + Ok(result.encode()) + } + "wifi_direct_fast_link_hosting" => { + let arg_link_id = args.take("link_id")?; + let arg_host = args.take("host")?; + let arg_port = args.take("port")?; + args.finish()?; + target.wifi_direct_fast_link_hosting(arg_link_id, arg_host, arg_port)?; + Ok(Value::Null) + } + "wifi_direct_fast_link_ended" => { + let arg_link_id = args.take("link_id")?; + let arg_reason = args.take("reason")?; + args.finish()?; + target.wifi_direct_fast_link_ended(arg_link_id, arg_reason); + Ok(Value::Null) + } "reticulum_status_changed" => { let arg_is_connected = args.take("is_connected")?; args.finish()?; diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index d15c52219..7d94cab0f 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -2579,6 +2579,57 @@ pub struct WifiDirectMessage { pub data: Vec, } +/// One fast-link instruction for the platform (ADR 0038). See the UDL. +#[derive(Clone)] +pub struct FastLinkDirective { + pub kind: String, + pub link_id: String, + pub peer_id: String, + pub ssid: Option, + pub passphrase: Option, + pub host: Option, + pub port: Option, + pub expires_in_ms: u64, + pub reason: Option, +} + +impl std::fmt::Debug for FastLinkDirective { + // Never the passphrase: it is a network credential (invariant 5 of the + // fast link state machine). + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FastLinkDirective") + .field("kind", &self.kind) + .field("link_id", &self.link_id) + .field("peer_id", &"[REDACTED]") + .field("ssid", &self.ssid) + .field( + "passphrase", + &self.passphrase.as_ref().map(|_| "[REDACTED]"), + ) + .field("host", &self.host) + .field("port", &self.port) + .field("expires_in_ms", &self.expires_in_ms) + .field("reason", &self.reason) + .finish() + } +} + +impl From for FastLinkDirective { + fn from(directive: offline_protocol::fast_link::FastLinkDirective) -> Self { + Self { + kind: directive.kind.as_str().to_string(), + link_id: directive.link_id, + peer_id: directive.peer_id, + ssid: directive.ssid, + passphrase: directive.passphrase, + host: directive.host, + port: directive.port, + expires_in_ms: directive.expires_in_ms, + reason: directive.reason.map(|reason| reason.as_str().to_string()), + } + } +} + /// Reticulum message for outgoing data #[derive(Debug, Clone)] pub struct ReticulumMessage { @@ -5293,6 +5344,8 @@ impl OfflineProtocol { // then finds no link and adds nothing (wifi_direct_peer_disconnected). if after == 0 { for link in before { + // The layer's end is the stream's end for a fast link too. + self.lock_inner()?.fast_link_stream_lost(&link.peer_id); if self.peer_linked_elsewhere(&link.peer_id, CoreTransportType::WiFiDirect) { continue; } @@ -5365,6 +5418,8 @@ impl OfflineProtocol { data: Vec, ) -> Result<(), ProtocolError> { let mut protocol = self.lock_inner()?; + // Traffic on the slot keeps a fast link off its idle limit. + protocol.fast_link_activity(&sender_id); if let Some(transport_arc) = protocol .transport_manager() .get_transport(CoreTransportType::WiFiDirect) @@ -5438,6 +5493,8 @@ impl OfflineProtocol { })? .unwrap_or_default(); self.emit_wifi_direct_switch(before, after); + // A fast link waiting for this peer's stream is up. + self.lock_inner()?.fast_link_stream_proved(&peer_id); self.notify_neighbor_reachable(&peer_id, "WiFiDirect", None) } @@ -5466,6 +5523,11 @@ impl OfflineProtocol { })? .unwrap_or_default(); self.emit_wifi_direct_switch(before, after); + // A fast link carried by this stream is over, whether or not the + // peer is still reachable some other way. + if held { + self.lock_inner()?.fast_link_stream_lost(&peer_id); + } // Reported once, and only when the peer is out of reach. A link the // layer already ended was reported by wifi_direct_status_changed, and @@ -7910,6 +7972,57 @@ impl OfflineProtocol { guard.block_user(&user_id).map_err(ProtocolError::from) } + /// Asks for a fast link to `peer_id` (ADR 0038). See the UDL. + pub fn request_fast_link(&self, peer_id: String) -> Result { + let mut guard = self.lock_inner()?; + guard + .request_fast_link(&peer_id) + .map_err(ProtocolError::from) + } + + /// Ends the fast link with `peer_id`. Returns whether there was one. + pub fn close_fast_link(&self, peer_id: String) -> bool { + self.lock_inner() + .map(|mut guard| guard.close_fast_link(&peer_id)) + .unwrap_or(false) + } + + /// The platform says what it can do for a fast link. + pub fn wifi_direct_set_fast_link_roles(&self, can_host: bool, can_join: bool) { + if let Ok(mut guard) = self.lock_inner() { + guard.set_fast_link_roles(can_host, can_join); + } + } + + /// The next fast-link instruction for the platform. + pub fn wifi_direct_next_fast_link_directive(&self) -> Option { + self.lock_inner() + .ok()? + .next_fast_link_directive() + .map(FastLinkDirective::from) + } + + /// The host's network is up, its listener on `host:port`. + pub fn wifi_direct_fast_link_hosting( + &self, + link_id: String, + host: String, + port: u16, + ) -> Result<(), ProtocolError> { + let mut guard = self.lock_inner()?; + guard + .fast_link_hosting(&link_id, &host, port) + .map_err(ProtocolError::from) + } + + /// The platform could not do what it was told, or can no longer hold the + /// link. + pub fn wifi_direct_fast_link_ended(&self, link_id: String, reason: String) { + if let Ok(mut guard) = self.lock_inner() { + guard.fast_link_ended(&link_id, &reason); + } + } + /// Unblock a previously blocked user. pub fn unblock_user(&self, user_id: String) -> Result<(), ProtocolError> { let mut guard = self.lock_inner()?; diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index 1e317ccab..0cdeee544 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1414,6 +1414,26 @@ interface OfflineProtocol { // from scratch. void internet_address_declaration_refused(string reason); + // Fast link (ADR 0038). Brings up a Wi-Fi network between this device and + // `peer_id`, a peer with a confirmed session that is reachable over a + // live direct link (Bluetooth LE) and has advertised the capability. One + // device hosts and the other joins, with credentials sealed in the + // session, and the stream over it fills the peer-stream slot, so traffic + // moves to it by ordinary transport selection. Returns the link id as + // soon as the first step is taken; the outcome arrives as + // `fast_link_changed` events. On iOS a join shows a system prompt and + // takes the phone off its own Wi-Fi while the link lasts, so this is the + // application's call, never automatic. Refused when the peer has not + // advertised it, there is no confirmed session or live direct link, a + // peer stream already reaches it, this device can neither host nor join, + // or a link with another peer is held. + [Throws=ProtocolError] + string request_fast_link(string peer_id); + + // Ends the fast link with `peer_id`, telling the peer and this device's + // platform. Returns whether there was one. + boolean close_fast_link(string peer_id); + // Peer-stream transport operations (the `wifi_direct` slot) // // A byte stream the platform established to exactly one peer: a Wi-Fi @@ -1464,6 +1484,33 @@ interface OfflineProtocol { [Throws=ProtocolError] void wifi_direct_peer_disconnected(string peer_id); + // Fast link, the platform's half (ADR 0038, + // docs/state-machines/fast-link.md). The platform declares what it can + // do once it knows its permissions: an Android device that can create a + // Wi-Fi Direct group with given credentials hosts and joins, an iPhone + // with the Hotspot Configuration entitlement joins. Until it does, both + // are false and every request is refused. + void wifi_direct_set_fast_link_roles(boolean can_host, boolean can_join); + + // The next instruction for the platform, drained alongside + // `wifi_direct_get_next_message` whenever the transport callback fires: + // `host` (bring up a network with `ssid` and `passphrase`, admit only + // `peer_id`, then report it), `join` (join it, dial `host:port`, claim + // `peer_id`) or `close` (end the stream and leave or remove the + // network). The passphrase must never be logged. + FastLinkDirective? wifi_direct_next_fast_link_directive(); + + // The host's network is up and its listener is on `host:port`, a private + // or link-local address on that network. The offer goes to the peer. + [Throws=ProtocolError] + void wifi_direct_fast_link_hosting(string link_id, string host, u16 port); + + // The platform could not do what it was told, or can no longer hold the + // link: `declined` (the user refused the join), `failed`, `host_failed`, + // or `background` (iOS drops a joined network 15 s after the app leaves + // the foreground). The peer is told. + void wifi_direct_fast_link_ended(string link_id, string reason); + // Reticulum transport callback (event-driven sending) void set_reticulum_transport_callback(ReticulumTransportCallback callback); @@ -2577,6 +2624,22 @@ dictionary WifiDirectMessage { sequence data; }; +// One fast-link instruction for the platform (ADR 0038). `kind` is `host`, +// `join` or `close`; the optional fields are set for the kinds that use +// them. `expires_in_ms` is how long the platform has to bring the network up +// (`host`) or prove the stream (`join`), and zero on `close`. +dictionary FastLinkDirective { + string kind; + string link_id; + string peer_id; + string? ssid; + string? passphrase; + string? host; + u16? port; + u64 expires_in_ms; + string? reason; +}; + // The signed proof a device presents to attach to a gateway: everything // DeclareAddress needs, already committed to the offline-gateway-addr-v1 // domain and the gateway's own challenge. diff --git a/docs/spec/local-api.md b/docs/spec/local-api.md index 5cb9a3927..f35f4fb0e 100644 --- a/docs/spec/local-api.md +++ b/docs/spec/local-api.md @@ -416,6 +416,19 @@ other client's sessions too. | `get_blocked_users` | | `[]` | | `is_user_blocked` | `user_id` | `!` | +### Engine: fast link + +A Wi-Fi network brought up between this instance and a peer it meets only +over Bluetooth LE ([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md)). +A host process can neither host nor join one, so on a server these are +refused unless its driver declared a role; the outcome of a request arrives +as `fast_link_changed` events. + +| Method | Params | Result | +|---|---|---| +| `request_fast_link` | `peer_id` | string (the link id) | +| `close_fast_link` | `peer_id` | `!` | + ### Engine: transports and metrics Read-only views of the instance. Everything here describes the whole server, @@ -555,7 +568,7 @@ this chapter asserts it. | `set_ble_transport_callback`, `set_wifi_direct_transport_callback`, `set_reticulum_transport_callback`, `set_nostr_transport_callback` | A callback interface has no JSON form, and each installs the driver of a carrier | | `ble_peer_discovered`, `ble_peer_lost`, `ble_peer_rssi`, `ble_node_hash`, `set_peer_rssi_events`, `ble_status_changed`, `ble_fragment_received`, `ble_get_next_fragment`, `ble_return_fragment`, `ble_get_peer_count`, `ble_set_peer_mtu`, `ble_clear_peer_mtu`, `ble_undersized_mtu_reports`, `ble_fragment_fallback_count`, `ble_recipient_not_among_peers_count`, `protocol_lock_diagnostics` | The Bluetooth LE driver's feed and drain, its signal readings and the switch the binding flips for them, and the host's lock diagnostics | | `internet_status_changed`, `internet_message_received`, `internet_get_next_message`, `internet_confirm_sent`, `internet_send_failed`, `internet_send_failed_with_reason`, `internet_peer_presence`, `internet_presence_watchlist`, `internet_relay_capabilities`, `internet_group_report_received`, `internet_address_declared`, `internet_address_declaration_refused` | The relay client's feed and drain, including the dedicated entry points the threat model's boundary 2 requires | -| `wifi_direct_status_changed`, `wifi_direct_message_received`, `wifi_direct_get_next_message`, `wifi_direct_peer_connected`, `wifi_direct_peer_disconnected` | The peer-stream driver's feed and drain | +| `wifi_direct_status_changed`, `wifi_direct_message_received`, `wifi_direct_get_next_message`, `wifi_direct_peer_connected`, `wifi_direct_peer_disconnected`, `wifi_direct_set_fast_link_roles`, `wifi_direct_next_fast_link_directive`, `wifi_direct_fast_link_hosting`, `wifi_direct_fast_link_ended` | The peer-stream driver's feed and drain, and the networks it brings up or joins for a fast link, whose directives carry a passphrase | | `reticulum_status_changed`, `reticulum_message_received`, `reticulum_get_next_message`, `reticulum_confirm_sent`, `reticulum_send_failed`, `reticulum_send_failed_with_reason`, `reticulum_address_declared`, `reticulum_address_declaration_refused`, `reticulum_gateway_capabilities`, `reticulum_peer_presence`, `reticulum_presence_watchlist` | The gateway client's feed and drain | | `nostr_status_changed`, `nostr_message_received`, `nostr_message_received_at`, `nostr_get_next_message`, `nostr_confirm_sent`, `nostr_send_failed`, `nostr_send_failed_with_reason`, `nostr_get_public_key`, `nostr_get_subscription_filter`, `nostr_get_next_query`, `nostr_query_event_received`, `nostr_query_completed` | The Nostr client's feed and drain | | `update_transport_metrics`, `remove_transport`, `set_battery_level`, `set_battery_state` | Facts about the host that only the host process knows | From 1677aff4b7f20d6cf5b751f660037482e97c2c05 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 06:06:41 +0530 Subject: [PATCH 07/81] perf(protocol): send sixteen media chunks in flight on the peer-stream slot a 1 mib file over a fast link took 8.0 to 8.7 s with four 32 kib chunks in flight: about 128 kib per acknowledgement round, so the transfer waited on receipts rather than on the link. the peer-stream slot now keeps sixteen in flight, 512 kib, well inside the 4 mib a platform manager queues per stream. every other slot keeps its window. --- crates/offline-protocol/src/constants.rs | 11 ++++++ crates/offline-protocol/src/protocol/send.rs | 4 +-- .../src/protocol/tests/fast_link.rs | 36 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/constants.rs b/crates/offline-protocol/src/constants.rs index 0c5875c75..d957c726b 100644 --- a/crates/offline-protocol/src/constants.rs +++ b/crates/offline-protocol/src/constants.rs @@ -128,6 +128,17 @@ pub const MEDIA_WINDOW_SIZE_INTERNET: usize = 8; /// Default maximum chunks in flight for media transfers. pub const DEFAULT_MEDIA_WINDOW_SIZE: usize = 4; +/// Maximum chunks in flight for media transfers on the peer-stream slot (a +/// Wi-Fi Direct group, a LAN, AWDL or a fast link). +/// +/// Sixteen 32 KiB chunks, 512 KiB in flight. At the default of four a 1 MiB +/// file over a fast link took 8.0 to 8.7 s on two phones (ADR 0038): about +/// 128 KiB per acknowledgement round, with receipts coalesced for up to +/// 500 ms, so the transfer waited on acknowledgements rather than on the link. +/// The platform managers queue up to 4 MiB per stream before dropping, so +/// the window stays well inside what a stream holds. +pub const MEDIA_WINDOW_SIZE_PEER_STREAM: usize = 16; + /// Maximum entries in the dedicated media outbox. /// Smaller than the main outbox since the sliding window limits in-flight chunks. pub const MAX_MEDIA_OUTBOX_ENTRIES: usize = 100; diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index c608c72bf..92224a094 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -2896,8 +2896,8 @@ impl OfflineProtocol { (CHUNK_SIZE_INTERNET, MEDIA_WINDOW_SIZE_INTERNET) } TransportType::WiFiDirect => { - use crate::constants::{DEFAULT_CHUNK_SIZE, DEFAULT_MEDIA_WINDOW_SIZE}; - (DEFAULT_CHUNK_SIZE, DEFAULT_MEDIA_WINDOW_SIZE) + use crate::constants::{DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM}; + (DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM) } TransportType::Reticulum => { // Reticulum is low-bandwidth (LoRa); use BLE-like chunk sizes. diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 62fe901f2..dab06cd5b 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -270,3 +270,39 @@ fn a_peer_that_cannot_host_says_so() { &("closed".to_string(), Some("cannot_host".to_string())) ); } + +/// A transfer pinned to the peer-stream slot leaves sixteen chunks before it +/// waits for an acknowledgement, not four: at four, a fast link spent its +/// time waiting on receipts rather than on the link (ADR 0038, decision 9). +#[test] +fn a_transfer_on_the_peer_stream_slot_fills_a_window_of_sixteen() { + use offline_protocol_core::ContentType; + use offline_protocol_transport::PeerLink; + + use crate::constants::{DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM}; + + let (mut alice, bob) = pair(); + let stream = MockTransport::new(TransportType::WiFiDirect); + stream.start().unwrap(); + stream.set_connected_peers(vec![PeerLink::new(bob.address.clone())]); + alice + .protocol + .transport_manager_mut() + .add_transport(TransportType::WiFiDirect, Box::new(stream.clone())); + alice.take_sent(); + + let file = vec![0x5a; DEFAULT_CHUNK_SIZE * 20]; + alice + .protocol + .send_media(&bob.address, file, "big.bin", ContentType::File, None) + .unwrap(); + + let chunks = stream + .sent_messages() + .into_iter() + .chain(stream.peer_sends().into_iter().map(|(_, message)| message)) + .filter(|message| message.content_type == ContentType::FileChunk) + .count(); + assert_eq!(chunks, MEDIA_WINDOW_SIZE_PEER_STREAM); + assert_eq!(MEDIA_WINDOW_SIZE_PEER_STREAM, 16); +} From 303028ea054c5cb0883a4e39a8274656383d2355 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 06:15:06 +0530 Subject: [PATCH 08/81] feat(bindings): host and join a fast link on android, and expose it to apps the android manager declares both roles on android 10 and later and drains the engine's directives on the transport callback. it hosts a wi-fi direct group with the engine's credentials and reports the owner's address and its listener's port once the group exists; it joins one by name and passphrase and dials the offered address and port claiming the host. while hosting, an inbound stream on the group must prove the invitee, and a group whose client has left ends its stream at once instead of waiting out keepalive. the phase 1 spike hooks are gone. requestFastLink and closeFastLink reach apps on react native and flutter on both platforms, through the generated bridges, the swift host bridge and the error manifest. the registration guard learns the callback's second post. --- .../flutter/EngineMethodHandlers.kt | 18 ++ .../flutter/FlutterEngineChannel.kt | 2 + .../ios/Classes/FlutterEngineChannel.swift | 4 + .../offline_protocol/lib/src/mesh_sdk.dart | 8 + .../lib/src/offline_protocol.dart | 2 + .../method_channel_methods.txt | 2 + .../java/com/offlineprotocol/FastLinkSpike.kt | 198 ------------ .../offlineprotocol/OfflineProtocolModule.kt | 12 + .../com/offlineprotocol/PeerStreamSockets.kt | 12 + .../com/offlineprotocol/ProtocolEngineHost.kt | 2 + .../ProtocolEngineHostBridge.kt | 12 + .../ProtocolEngineHostBridgeReactNative.kt | 12 + .../com/offlineprotocol/WifiDirectManager.kt | 292 ++++++++++++++++-- .../offlineprotocol/PeerStreamSocketsTest.kt | 30 ++ .../react-native/ios/OfflineProtocolModule.m | 9 + .../ios/OfflineProtocolModule.swift | 14 + .../ios/ProtocolEngineHostBridge.swift | 12 + .../ProtocolEngineHostBridgeReactNative.swift | 12 + bindings/react-native/src/index.ts | 36 +++ crates/offline-protocol-uniffi/src/lib.rs | 12 +- tools/gen_engine_method_handlers.py | 2 + tools/gen_protocol_engine_host_bridge.py | 18 ++ tools/rn_engine_bridge_error_manifest.json | 9 + 23 files changed, 512 insertions(+), 218 deletions(-) delete mode 100644 bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt diff --git a/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/EngineMethodHandlers.kt b/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/EngineMethodHandlers.kt index 8fbd1f64a..c9d649d41 100644 --- a/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/EngineMethodHandlers.kt +++ b/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/EngineMethodHandlers.kt @@ -91,6 +91,15 @@ internal object EngineMethodHandlers { return com.offlineprotocol.ProtocolEngineHostBridge.clearServiceTopic(host, env.context, arguments) } + @JvmStatic + fun closeFastLink( + host: ProtocolEngineHost, + env: FlutterEngineChannel.Environment, + arguments: Any?, + ): Any? { + return com.offlineprotocol.ProtocolEngineHostBridge.closeFastLink(host, env.context, arguments) + } + @JvmStatic fun create( host: ProtocolEngineHost, @@ -1338,6 +1347,15 @@ internal object EngineMethodHandlers { return com.offlineprotocol.ProtocolEngineHostBridge.requestEnableBluetooth(host, activity, arguments) } + @JvmStatic + fun requestFastLink( + host: ProtocolEngineHost, + env: FlutterEngineChannel.Environment, + arguments: Any?, + ): Any? { + return com.offlineprotocol.ProtocolEngineHostBridge.requestFastLink(host, env.context, arguments) + } + @JvmStatic fun resolveUsername( host: ProtocolEngineHost, diff --git a/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/FlutterEngineChannel.kt b/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/FlutterEngineChannel.kt index 020943941..c1d810378 100644 --- a/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/FlutterEngineChannel.kt +++ b/bindings/flutter/offline_protocol/android/src/main/kotlin/com/offlineprotocol/flutter/FlutterEngineChannel.kt @@ -41,6 +41,7 @@ object FlutterEngineChannel { "cancelFileTransfer" -> EngineMethodHandlers.cancelFileTransfer(host, env, arguments) "checkInternetPresence" -> EngineMethodHandlers.checkInternetPresence(host, env, arguments) "clearServiceTopic" -> EngineMethodHandlers.clearServiceTopic(host, env, arguments) + "closeFastLink" -> EngineMethodHandlers.closeFastLink(host, env, arguments) "create" -> EngineMethodHandlers.create(host, env, arguments) "createInvite" -> EngineMethodHandlers.createInvite(host, env, arguments) "dataAttachmentHash" -> EngineMethodHandlers.dataAttachmentHash(host, env, arguments) @@ -169,6 +170,7 @@ object FlutterEngineChannel { "releaseTransportLock" -> EngineMethodHandlers.releaseTransportLock(host, env, arguments) "replayEvents" -> EngineMethodHandlers.replayEvents(host, env, arguments) "requestEnableBluetooth" -> EngineMethodHandlers.requestEnableBluetooth(host, env, arguments) + "requestFastLink" -> EngineMethodHandlers.requestFastLink(host, env, arguments) "resolveUsername" -> EngineMethodHandlers.resolveUsername(host, env, arguments) "respondToServiceRequest" -> EngineMethodHandlers.respondToServiceRequest(host, env, arguments) "resume" -> EngineMethodHandlers.resume(host, env, arguments) diff --git a/bindings/flutter/offline_protocol/ios/Classes/FlutterEngineChannel.swift b/bindings/flutter/offline_protocol/ios/Classes/FlutterEngineChannel.swift index 97b00ca79..ec68cb6aa 100644 --- a/bindings/flutter/offline_protocol/ios/Classes/FlutterEngineChannel.swift +++ b/bindings/flutter/offline_protocol/ios/Classes/FlutterEngineChannel.swift @@ -37,6 +37,8 @@ enum FlutterEngineChannel { return try ProtocolEngineHostBridge.checkInternetPresence(host: host, env: env, arguments: arguments) case "clearServiceTopic": return try ProtocolEngineHostBridge.clearServiceTopic(host: host, env: env, arguments: arguments) + case "closeFastLink": + return try ProtocolEngineHostBridge.closeFastLink(host: host, env: env, arguments: arguments) case "create": return try ProtocolEngineHostBridge.create(host: host, env: env, arguments: arguments) case "createInvite": @@ -297,6 +299,8 @@ enum FlutterEngineChannel { return try ProtocolEngineHostBridge.replayEvents(host: host, env: env, arguments: arguments) case "requestEnableBluetooth": return try ProtocolEngineHostBridge.requestEnableBluetooth(host: host, env: env, arguments: arguments) + case "requestFastLink": + return try ProtocolEngineHostBridge.requestFastLink(host: host, env: env, arguments: arguments) case "resolveUsername": return try ProtocolEngineHostBridge.resolveUsername(host: host, env: env, arguments: arguments) case "respondToServiceRequest": diff --git a/bindings/flutter/offline_protocol/lib/src/mesh_sdk.dart b/bindings/flutter/offline_protocol/lib/src/mesh_sdk.dart index 7f0170bc1..4ae1f0594 100644 --- a/bindings/flutter/offline_protocol/lib/src/mesh_sdk.dart +++ b/bindings/flutter/offline_protocol/lib/src/mesh_sdk.dart @@ -48,6 +48,10 @@ static Future checkInternetPresence([Map? args]) => static Future clearServiceTopic([Map? args]) => _invoke('clearServiceTopic', args); +/// Native `closeFastLink` (see React Native `OfflineProtocolNativeModule.closeFastLink`). +static Future closeFastLink([Map? args]) => + _invoke('closeFastLink', args); + /// Native `createInvite` (see React Native `OfflineProtocolNativeModule.createInvite`). static Future createInvite([Map? args]) => _invoke('createInvite', args); @@ -536,6 +540,10 @@ static Future releaseTransportLock([Map? args]) => static Future requestEnableBluetooth([Map? args]) => _invoke('requestEnableBluetooth', args); +/// Native `requestFastLink` (see React Native `OfflineProtocolNativeModule.requestFastLink`). +static Future requestFastLink([Map? args]) => + _invoke('requestFastLink', args); + /// Native `resolveUsername` (see React Native `OfflineProtocolNativeModule.resolveUsername`). static Future resolveUsername([Map? args]) => _invoke('resolveUsername', args); diff --git a/bindings/flutter/offline_protocol/lib/src/offline_protocol.dart b/bindings/flutter/offline_protocol/lib/src/offline_protocol.dart index 1e1e87e26..43d8687f0 100644 --- a/bindings/flutter/offline_protocol/lib/src/offline_protocol.dart +++ b/bindings/flutter/offline_protocol/lib/src/offline_protocol.dart @@ -141,6 +141,7 @@ class OfflineProtocol { 'cancelFileTransfer', 'checkInternetPresence', 'clearServiceTopic', + 'closeFastLink', 'create', 'createInvite', 'dataAttachmentHash', @@ -269,6 +270,7 @@ class OfflineProtocol { 'releaseTransportLock', 'replayEvents', 'requestEnableBluetooth', + 'requestFastLink', 'resolveUsername', 'respondToServiceRequest', 'resume', diff --git a/bindings/flutter/offline_protocol/method_channel_methods.txt b/bindings/flutter/offline_protocol/method_channel_methods.txt index 4ca7e2faf..bbfd15e2b 100644 --- a/bindings/flutter/offline_protocol/method_channel_methods.txt +++ b/bindings/flutter/offline_protocol/method_channel_methods.txt @@ -7,6 +7,7 @@ cancelConnectionRequest cancelFileTransfer checkInternetPresence clearServiceTopic +closeFastLink create createInvite dataAttachmentHash @@ -135,6 +136,7 @@ rekeySession releaseTransportLock replayEvents requestEnableBluetooth +requestFastLink resolveUsername respondToServiceRequest resume diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt deleted file mode 100644 index bb7b1b1fc..000000000 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/FastLinkSpike.kt +++ /dev/null @@ -1,198 +0,0 @@ -package com.offlineprotocol - -import android.annotation.SuppressLint -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent -import android.content.IntentFilter -import android.net.ConnectivityManager -import android.net.wifi.WifiManager -import android.net.wifi.p2p.WifiP2pConfig -import android.net.wifi.p2p.WifiP2pManager -import android.os.Build -import android.os.Handler -import android.os.Looper -import android.os.SystemClock -import android.util.Log -import java.net.Inet4Address -import java.net.NetworkInterface - -/** - * SPIKE (BLE-to-Wi-Fi fast link, phase 1). Throwaway: not a design. - * - * Driven from adb so the spike needs no UDL or JS surface: - * - * adb shell am broadcast -a com.offlineprotocol.SPIKE_FAST_LINK \ - * --es op host --es ssid DIRECT-sp-fastlink --es pass [--ei band 2|5] - * ... --es op lohs (LocalOnlyHotspot; the system picks the credentials) - * ... --es op info (group, Wi-Fi and interface state) - * ... --es op stop (remove the group, close the hotspot) - * ... --es op nolan (stop the LAN carrier: no shared network) - * - * Everything it learns goes to logcat under [TAG]. The peer stream itself is - * the manager's: its listener binds every interface on the group port, so an - * iPhone that joins the group or the hotspot dials it like any other. - */ -internal class FastLinkSpike( - private val context: Context, - /** Stops the LAN carrier, so a pair on one Wi-Fi network meets only over BLE. */ - private val stopLan: () -> Unit = {}, -) { - companion object { - const val TAG = "OPSPIKE" - const val ACTION = "com.offlineprotocol.SPIKE_FAST_LINK" - } - - private val handler = Handler(Looper.getMainLooper()) - private val p2p = context.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager - private val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager - private var channel: WifiP2pManager.Channel? = null - private var reservation: WifiManager.LocalOnlyHotspotReservation? = null - private var t0 = 0L - - private val receiver = object : BroadcastReceiver() { - override fun onReceive(c: Context, intent: Intent) { - val op = intent.getStringExtra("op") ?: "info" - log("op=$op") - when (op) { - "host" -> host( - intent.getStringExtra("ssid") ?: "DIRECT-sp-fastlink", - intent.getStringExtra("pass") ?: "", - intent.getIntExtra("band", 0), - ) - "lohs" -> lohs() - "stop" -> stopAll() - "nolan" -> stopLan() - else -> info() - } - } - } - - fun register() { - val filter = IntentFilter(ACTION) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED) - } else { - context.registerReceiver(receiver, filter) - } - log("registered") - } - - fun unregister() { - try { context.unregisterReceiver(receiver) } catch (_: Exception) {} - stopAll() - channel?.close() - channel = null - } - - private fun log(message: String) { - val since = if (t0 == 0L) 0 else SystemClock.elapsedRealtime() - t0 - Log.i(TAG, "wall=${System.currentTimeMillis()} +${since}ms $message") - } - - private fun ch(): WifiP2pManager.Channel? { - if (channel == null) channel = p2p?.initialize(context, Looper.getMainLooper(), null) - return channel - } - - @SuppressLint("MissingPermission") - private fun host(ssid: String, pass: String, band: Int) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { log("host needs API 29"); return } - val p2p = p2p ?: run { log("no p2p"); return } - val ch = ch() ?: run { log("no channel"); return } - t0 = SystemClock.elapsedRealtime() - val builder = WifiP2pConfig.Builder() - .setNetworkName(ssid) - .setPassphrase(pass) - .enablePersistentMode(false) - when (band) { - 2 -> builder.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_2GHZ) - 5 -> builder.setGroupOperatingBand(WifiP2pConfig.GROUP_OWNER_BAND_5GHZ) - } - val config = builder.build() - // Whatever group exists goes first: createGroup fails BUSY beside one. - p2p.removeGroup(ch, object : WifiP2pManager.ActionListener { - override fun onSuccess() = create() - override fun onFailure(reason: Int) = create() - fun create() { - log("createGroup ssid=$ssid band=$band") - p2p.createGroup(ch, config, object : WifiP2pManager.ActionListener { - override fun onSuccess() { - log("createGroup ok") - handler.postDelayed({ info() }, 1500) - handler.postDelayed({ info() }, 5000) - } - override fun onFailure(reason: Int) = log("createGroup failed reason=$reason") - }) - } - }) - } - - @SuppressLint("MissingPermission") - private fun lohs() { - val wifi = wifi ?: run { log("no wifi"); return } - t0 = SystemClock.elapsedRealtime() - try { - wifi.startLocalOnlyHotspot(object : WifiManager.LocalOnlyHotspotCallback() { - override fun onStarted(r: WifiManager.LocalOnlyHotspotReservation) { - reservation = r - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - val c = r.softApConfiguration - log("lohs started ssid=${c.ssid} pass=${c.passphrase} security=${c.securityType}") - } else { - @Suppress("DEPRECATION") - val c = r.wifiConfiguration - log("lohs started ssid=${c?.SSID} pass=${c?.preSharedKey}") - } - handler.postDelayed({ info() }, 1500) - } - override fun onStopped() = log("lohs stopped") - override fun onFailed(reason: Int) = log("lohs failed reason=$reason") - }, handler) - } catch (e: Exception) { - log("lohs threw ${e.javaClass.simpleName}: ${e.message}") - } - } - - @SuppressLint("MissingPermission") - private fun stopAll() { - reservation?.close() - reservation = null - val ch = channel ?: return - p2p?.removeGroup(ch, object : WifiP2pManager.ActionListener { - override fun onSuccess() = log("group removed") - override fun onFailure(reason: Int) = log("remove group failed reason=$reason") - }) - } - - @SuppressLint("MissingPermission") - private fun info() { - val ch = ch() - if (ch != null) { - p2p?.requestGroupInfo(ch) { g -> - if (g == null) { - log("group none") - } else { - val freq = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) g.frequency else -1 - log("group name=${g.networkName} pass=${g.passphrase} owner=${g.isGroupOwner} " + - "iface=${g.`interface`} freq=$freq clients=${g.clientList.size}") - } - } - } - @Suppress("DEPRECATION") - val ci = wifi?.connectionInfo - @Suppress("DEPRECATION") - log("wifi enabled=${wifi?.isWifiEnabled} sta ssid=${ci?.ssid} freq=${ci?.frequency} rssi=${ci?.rssi}") - val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager - log("default network=${cm?.activeNetwork}") - try { - for (nif in NetworkInterface.getNetworkInterfaces()) { - if (!nif.isUp) continue - val v4 = nif.inetAddresses.toList().filterIsInstance() - if (v4.isNotEmpty()) log("iface ${nif.name} ${v4.joinToString { it.hostAddress ?: "?" }}") - } - } catch (e: Exception) { - log("interfaces: ${e.message}") - } - } -} diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/OfflineProtocolModule.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/OfflineProtocolModule.kt index a36095447..2b14ef322 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/OfflineProtocolModule.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/OfflineProtocolModule.kt @@ -1598,6 +1598,18 @@ class OfflineProtocolModule(reactContext: ReactApplicationContext) : ProtocolEngineHostBridgeReactNative.cancelConnectionRequest(this, recipient, promise) } + // Fast link (ADR 0038) + + @ReactMethod + fun requestFastLink(peerId: String, promise: Promise) { + ProtocolEngineHostBridgeReactNative.requestFastLink(this, peerId, promise) + } + + @ReactMethod + fun closeFastLink(peerId: String, promise: Promise) { + ProtocolEngineHostBridgeReactNative.closeFastLink(this, peerId, promise) + } + // User Blocking @ReactMethod diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt index 6806f8df0..e4243dea1 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt @@ -168,6 +168,14 @@ internal class PeerStreamSockets( */ @Volatile var onLost: ((String) -> Unit)? = null + /** + * Whether an inbound stream that proved `address` on `carrier` may be + * announced. Null admits everything, as before. A fast-link host sets it + * while its network is up, so a device that got onto that network proves + * the invitee's address or is closed (ADR 0038). + */ + @Volatile var admitsInbound: ((address: String, carrier: Carrier) -> Boolean)? = null + /** Whether a stream holds [address] now. */ fun holds(address: String): Boolean = links.handleFor(address) != null @@ -276,6 +284,10 @@ internal class PeerStreamSockets( // Proved even if the held stream wins below: the peer is who it // said, and the dial that found it needs no ladder. proved = address + if (!outbound && admitsInbound?.invoke(address, carrier) == false) { + why = "not invited onto this network" + return ran() + } if (!announce(stream, address, outbound)) { why = "ended or refused before the announcement" return ran() diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt index c2ce8851c..abd77a78d 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt @@ -410,6 +410,8 @@ class ProtocolEngineHost( proto.setWifiDirectTransportCallback(object : uniffi.offline_protocol.WifiDirectTransportCallback { override fun onMessagesAvailable() { wifiDirectManager?.onMessagesAvailable() + // The same wake carries fast-link directives (ADR 0038). + wifiDirectManager?.onFastLinkWake() } }) onDiagnostic("info", "WiFi Direct transport callback registered", emptyMap()) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridge.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridge.kt index 94ba5945e..b338c8f93 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridge.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridge.kt @@ -313,6 +313,12 @@ object ProtocolEngineHostBridge { return null } + /** Ends the fast link with `peerId`; returns whether there was one. */ + fun closeFastLink(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { + val map = mapFromAny(arguments) + return host.requireProtocolBridge().closeFastLink(requireString(map, "peerId")) + } + fun createInvite(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { val map = mapFromAny(arguments) @@ -963,6 +969,12 @@ object ProtocolEngineHostBridge { } + /** Asks for a fast link to `peerId` (ADR 0038); returns the link id. */ + fun requestFastLink(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { + val map = mapFromAny(arguments) + return host.requireProtocolBridge().requestFastLink(requireString(map, "peerId")) + } + fun resolveUsername(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { val map = mapFromAny(arguments) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt index d8d182cd4..ecc112237 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt @@ -68,6 +68,18 @@ fun bleGetPeerCount(module: OfflineProtocolModule, promise: Promise) { } } +fun requestFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { + run(module, promise, "ERROR_FAST_LINK", "Failed to request a fast link", mapProtocolErrors = true) { host, context -> + ProtocolEngineHostBridge.requestFastLink(host, context, mapOf("peerId" to peerId)) + } +} + +fun closeFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { + run(module, promise, "ERROR_FAST_LINK", "Failed to close the fast link") { host, context -> + ProtocolEngineHostBridge.closeFastLink(host, context, mapOf("peerId" to peerId)) + } +} + fun blockUser(module: OfflineProtocolModule, userId: String, promise: Promise) { run(module, promise, "ERROR_BLOCK_USER", "Failed to block user") { host, context -> ProtocolEngineHostBridge.blockUser(host, context, mapOf("userId" to userId)) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index f9bfb930d..c84920b30 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -16,6 +16,7 @@ import android.util.Log import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest import androidx.core.content.ContextCompat +import uniffi.offline_protocol.FastLinkDirective import uniffi.offline_protocol.OfflineProtocol import uniffi.offline_protocol.verifyIdentityAssertion import java.io.* @@ -143,6 +144,9 @@ class WifiDirectManager( // about six seconds before it associates, and the supplicant retries a // rejected association; an eight-second window cut that retry off. private const val JOIN_WINDOW_MS = 15_000L + // Fast-link directives one drain pass runs; the engine queues at most + // a few per link. + private const val MAX_FAST_LINK_DIRECTIVES = 8 } /** @@ -187,8 +191,6 @@ class WifiDirectManager( // Whether the listener holds the port a group's clients dial. Written at // start, read by formation on the transport thread. private var ownsGroupPort = false - // SPIKE(fast-link) - private var spike: FastLinkSpike? = null // Every socket from its first byte to its end: the preamble, the framing, // one announced stream per address, the writers. This manager owns the @@ -515,15 +517,12 @@ class WifiDirectManager( // Start server socket on the port bound above. startServerSocket(listener) - // SPIKE(fast-link): adb-driven group and hotspot hosting. - spike = FastLinkSpike(context) { - transportHandler.post { - lan?.stop() - lan = null - sockets.closeCarrier(PeerStreamSockets.Carrier.LAN) - Log.i(FastLinkSpike.TAG, "LAN carrier stopped") - } - }.also { it.register() } + // A fast-link host admits only its invitee on the network it made. + sockets.admitsInbound = { address, carrier -> + val hosted = fastLinkHosted + carrier != PeerStreamSockets.Carrier.P2P || hosted == null || hosted.peer == address + } + declareFastLinkRoles(p2p) updateState(TransportState.RUNNING) @@ -607,8 +606,7 @@ class WifiDirectManager( // Stop server socket stopServerSocket() - spike?.unregister() - spike = null + endFastLinkOnStop() lan?.stop() lan = null @@ -921,7 +919,9 @@ class WifiDirectManager( "groupOwnerAddress" to (groupOwnerAddress ?: "null") )) + if (isGroupOwner) fastLinkGroupChanged() if (!isGroupOwner && groupOwnerAddress != null) { + fastLinkJoined?.connected = true // Connect to group owner connectToGroupOwner(groupOwnerAddress!!) } @@ -939,6 +939,8 @@ class WifiDirectManager( appGroupOwnerDevice = null unprovedAtCeiling.set(0) ownerIdleSinceMs = 0L + // Posted for the reason the stream close below is: an FFI call. + transportHandler.post { fastLinkGroupGone() } // Posted: this is the broadcast receiver's onReceive, and ending // an announced stream is an FFI call. Same reasoning as the post // in [handleWifiP2pStateChanged]. Leaving the group ends only the @@ -1418,6 +1420,248 @@ class WifiDirectManager( } } + // MARK: - Fast link (ADR 0038) + + /** A network this device brought up for one peer. Transport thread. */ + private class FastLinkHosted(val linkId: String, val peer: String, val ssid: String) { + var reported = false + var sawClient = false + } + + /** A network this device joins for one peer. */ + private class FastLinkJoined( + val linkId: String, + val peer: String, + val host: String, + val port: Int, + ) { + @Volatile var connected = false + } + + // Written on the transport thread; read by the socket threads (the + // admission check, the dial). + @Volatile private var fastLinkHosted: FastLinkHosted? = null + @Volatile private var fastLinkJoined: FastLinkJoined? = null + + /** A group by name and passphrase, for creating or joining: Android 10. */ + private val fastLinkSupported: Boolean + get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q + + /** + * Tells the engine what this device can do: with Wi-Fi P2P permitted on + * Android 10 and later, both host and join. + */ + private fun declareFastLinkRoles(p2p: Boolean) { + val able = p2p && fastLinkSupported + try { + protocol.wifiDirectSetFastLinkRoles(able, able) + } catch (e: Exception) { + Log.w(TAG, "Could not declare fast-link roles", e) + } + } + + /** + * The engine's wake-up, for its fast-link directives: posted like the + * body drain, and paused with it. Separate from [onMessagesAvailable], + * whose drain stops at "no stream yet", because a directive is what + * brings the first stream up. A paused transport answers when the poll + * resumes, and the engine's timers cover the wait. + */ + fun onFastLinkWake() { + if (isPaused) return + transportHandler.post { drainFastLinkDirectives() } + } + + /** Runs what the engine asked for. Transport thread. */ + private fun drainFastLinkDirectives() { + if (state != TransportState.RUNNING) return + repeat(MAX_FAST_LINK_DIRECTIVES) { + val directive = try { + protocol.wifiDirectNextFastLinkDirective() + } catch (e: Exception) { + null + } ?: return + when (directive.kind) { + "host" -> hostFastLink(directive) + "join" -> joinFastLink(directive) + "close" -> closeFastLink(directive.linkId) + } + } + } + + private fun fastLinkEnded(linkId: String, reason: String) { + try { + protocol.wifiDirectFastLinkEnded(linkId, reason) + } catch (e: Exception) { + Log.w(TAG, "Could not report a fast-link end", e) + } + } + + private fun fastLinkConfig(ssid: String, passphrase: String): WifiP2pConfig? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null + return WifiP2pConfig.Builder() + .setNetworkName(ssid) + .setPassphrase(passphrase) + .enablePersistentMode(false) + .build() + } + + /** + * Brings up a group with the engine's credentials. Reported to the engine + * from [fastLinkGroupChanged], once the group exists and has an address. + * Never while another group is held: a device owns at most one. + */ + @SuppressLint("MissingPermission") + private fun hostFastLink(directive: FastLinkDirective) { + val ssid = directive.ssid + val passphrase = directive.passphrase + val p2p = wifiP2pManager + val ch = channel + val config = if (ssid != null && passphrase != null) fastLinkConfig(ssid, passphrase) else null + if (config == null || ssid == null || p2p == null || ch == null || inGroup || + fastLinkHosted != null || fastLinkJoined != null + ) { + fastLinkEnded(directive.linkId, "host_failed") + return + } + val hosted = FastLinkHosted(directive.linkId, directive.peerId, ssid) + fastLinkHosted = hosted + emitDiagnostic("info", "Fast link: bringing up a network", mapOf("linkId" to directive.linkId)) + p2p.createGroup(ch, config, object : WifiP2pManager.ActionListener { + override fun onSuccess() {} + override fun onFailure(reason: Int) { + if (fastLinkHosted !== hosted) return + fastLinkHosted = null + emitDiagnostic("warning", "Fast link: the network did not come up", mapOf( + "reason" to reasonToString(reason), + )) + fastLinkEnded(hosted.linkId, "host_failed") + } + }) + } + + /** + * Joins the offered group by name and passphrase. Once in it, + * [connectToGroupOwner] dials the offered address and port, claiming the + * host. + */ + @SuppressLint("MissingPermission") + private fun joinFastLink(directive: FastLinkDirective) { + val ssid = directive.ssid + val passphrase = directive.passphrase + val host = directive.host + val port = directive.port?.toInt() + val p2p = wifiP2pManager + val ch = channel + val config = if (ssid != null && passphrase != null) fastLinkConfig(ssid, passphrase) else null + if (config == null || host == null || port == null || p2p == null || ch == null || inGroup || + fastLinkHosted != null || fastLinkJoined != null + ) { + fastLinkEnded(directive.linkId, "failed") + return + } + val joined = FastLinkJoined(directive.linkId, directive.peerId, host, port) + fastLinkJoined = joined + emitDiagnostic("info", "Fast link: joining a network", mapOf("linkId" to directive.linkId)) + p2p.connect(ch, config, object : WifiP2pManager.ActionListener { + override fun onSuccess() {} + override fun onFailure(reason: Int) { + if (fastLinkJoined !== joined) return + fastLinkJoined = null + emitDiagnostic("warning", "Fast link: the join was refused", mapOf( + "reason" to reasonToString(reason), + )) + fastLinkEnded(joined.linkId, "failed") + } + }) + } + + /** Ends what this device holds for the link: leaves or removes the group. */ + @SuppressLint("MissingPermission") + private fun closeFastLink(linkId: String) { + val p2p = wifiP2pManager ?: return + val ch = channel ?: return + val hosted = fastLinkHosted + val joined = fastLinkJoined + if (hosted?.linkId == linkId) { + fastLinkHosted = null + p2p.removeGroup(ch, quietListener("remove fast-link group")) + } + if (joined?.linkId == linkId) { + fastLinkJoined = null + if (!joined.connected) p2p.cancelConnect(ch, quietListener("cancel fast-link join")) + p2p.removeGroup(ch, quietListener("leave fast-link group")) + } + } + + /** + * The group this device owns changed. The first time the fast link's + * group is seen with an address, the engine is told and the offer goes + * out; after that a group whose client has gone means the joiner left the + * network, so its stream is ended now rather than when keepalive notices, + * about 40 s later. + */ + @SuppressLint("MissingPermission") + private fun fastLinkGroupChanged() { + val hosted = fastLinkHosted ?: return + wifiP2pManager?.requestGroupInfo(channel) { group -> + if (fastLinkHosted !== hosted || group == null || !group.isGroupOwner || + group.networkName != hosted.ssid + ) { + return@requestGroupInfo + } + val clients = group.clientList.size + if (clients > 0) hosted.sawClient = true + if (!hosted.reported) { + val port = serverSocket?.localPort + val host = groupOwnerAddress + if (port == null || host == null) return@requestGroupInfo + hosted.reported = true + try { + protocol.wifiDirectFastLinkHosting(hosted.linkId, host, port.toUShort()) + } catch (e: Exception) { + emitDiagnostic("warning", "Fast link: the engine refused the network", mapOf( + "error" to (e.message ?: "unknown"), + )) + } + } else if (hosted.sawClient && clients == 0) { + sockets.closeCarrier(PeerStreamSockets.Carrier.P2P) + } + } + } + + /** This device left whatever group it was in. */ + private fun fastLinkGroupGone() { + val hosted = fastLinkHosted + if (hosted != null && hosted.reported) { + fastLinkHosted = null + fastLinkEnded(hosted.linkId, "lost") + } + val joined = fastLinkJoined + if (joined != null && joined.connected) { + fastLinkJoined = null + fastLinkEnded(joined.linkId, "lost") + } + } + + /** The transport is stopping: anything held for a link goes with it. */ + @SuppressLint("MissingPermission") + private fun endFastLinkOnStop() { + val hosted = fastLinkHosted + val joined = fastLinkJoined + fastLinkHosted = null + fastLinkJoined = null + val ch = channel + if ((hosted != null || joined != null) && ch != null) { + wifiP2pManager?.removeGroup(ch, quietListener("end fast link on stop")) + } + hosted?.let { fastLinkEnded(it.linkId, "failed") } + joined?.let { fastLinkEnded(it.linkId, "failed") } + try { + protocol.wifiDirectSetFastLinkRoles(false, false) + } catch (_: Exception) {} + } + // MARK: - Socket Operations private fun startServerSocket(listener: PeerStreamListener.Bound) { @@ -1498,10 +1742,17 @@ class WifiDirectManager( socketExecutor.execute { var ran = PeerStreamSockets.Ran(proved = null, heard = false) try { + // A fast link names the owner's address, port and identity in + // its offer; any other group's owner is dialled on the group + // port and proves whoever it is. + val joined = fastLinkJoined val socket = Socket() try { socket.connect( - InetSocketAddress(address, PeerStreamListener.GROUP_OWNER_PORT), + InetSocketAddress( + joined?.host ?: address, + joined?.port ?: PeerStreamListener.GROUP_OWNER_PORT, + ), CONNECTION_TIMEOUT_MS.toInt(), ) } catch (e: Exception) { @@ -1515,10 +1766,14 @@ class WifiDirectManager( emitDiagnostic("info", "Connected to group owner", mapOf( "address" to address )) - // No claim to compare against: the owner's IP says nothing - // about who it is, so the address its preamble derives is its - // id (stream-framing.md, "The preamble"). - ran = sockets.run(socket, outbound = true) { state == TransportState.RUNNING } + // Outside a fast link there is no claim to compare against: + // the owner's IP says nothing about who it is, so the address + // its preamble derives is its id (stream-framing.md, "The + // preamble"). A fast link's offer names the host, and a + // preamble proving anyone else closes the stream. + ran = sockets.run(socket, outbound = true, expected = joined?.peer) { + state == TransportState.RUNNING + } } finally { outboundOpen.set(false) scheduleReconnect(address, ran) @@ -1742,6 +1997,7 @@ class WifiDirectManager( } private fun pollAndSendMessages() { + drainFastLinkDirectives() if (state != TransportState.RUNNING || sockets.isEmpty()) return try { diff --git a/bindings/react-native/android/src/test/java/com/offlineprotocol/PeerStreamSocketsTest.kt b/bindings/react-native/android/src/test/java/com/offlineprotocol/PeerStreamSocketsTest.kt index 29cf6c6a7..3dad5018e 100644 --- a/bindings/react-native/android/src/test/java/com/offlineprotocol/PeerStreamSocketsTest.kt +++ b/bindings/react-native/android/src/test/java/com/offlineprotocol/PeerStreamSocketsTest.kt @@ -212,6 +212,36 @@ class PeerStreamSocketsTest { assertNull(host.quiet()) } + @Test + fun `a fast-link host admits only its invitee on the network it made`() { + val host = Host("peer-a") + val sockets = PeerStreamSockets(host, fast) + sockets.admitsInbound = { address, carrier -> + carrier != PeerStreamSockets.Carrier.P2P || address == "peer-invited" + } + val group = listen(sockets, PeerStreamSockets.Carrier.P2P) + val lan = listen(sockets, PeerStreamSockets.Carrier.LAN) + + // A device that got onto the network proves someone else: closed, + // never announced. + val stranger = raw(group) + stranger.readBody() + stranger.send(assertion("peer-stranger")) + assertTrue(stranger.closedByPeer()) + assertNull(host.quiet()) + + // The same address on another carrier is not the host's to judge. + val neighbour = raw(lan) + neighbour.readBody() + neighbour.send(assertion("peer-stranger")) + assertEquals("connected:peer-stranger", host.next()) + + val invited = raw(group) + invited.readBody() + invited.send(assertion("peer-invited")) + assertEquals("connected:peer-invited", host.next()) + } + @Test fun `a message before any preamble is refused`() { // The chapter's vector: a well-formed message frame as the first frame. diff --git a/bindings/react-native/ios/OfflineProtocolModule.m b/bindings/react-native/ios/OfflineProtocolModule.m index a700e260f..b9d9970fa 100644 --- a/bindings/react-native/ios/OfflineProtocolModule.m +++ b/bindings/react-native/ios/OfflineProtocolModule.m @@ -445,6 +445,15 @@ @interface RCT_EXTERN_MODULE(OfflineProtocolModule, RCTEventEmitter) resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) +// Fast link (ADR 0038) +RCT_EXTERN_METHOD(requestFastLink:(NSString *)peerId + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) + +RCT_EXTERN_METHOD(closeFastLink:(NSString *)peerId + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) + // User Blocking RCT_EXTERN_METHOD(blockUser:(NSString *)userId resolver:(RCTPromiseResolveBlock)resolve diff --git a/bindings/react-native/ios/OfflineProtocolModule.swift b/bindings/react-native/ios/OfflineProtocolModule.swift index 3d3b99ac6..bb3cc1eb9 100644 --- a/bindings/react-native/ios/OfflineProtocolModule.swift +++ b/bindings/react-native/ios/OfflineProtocolModule.swift @@ -2185,6 +2185,20 @@ class OfflineProtocolModule: RCTEventEmitter { ProtocolEngineHostBridgeReactNative.serviceSubscribers(self, serviceId, resolver: resolver, rejecter: rejecter) } + // MARK: - Fast link (ADR 0038) + + @objc func requestFastLink(_ peerId: String, + resolver: @escaping RCTPromiseResolveBlock, + rejecter: @escaping RCTPromiseRejectBlock) { + ProtocolEngineHostBridgeReactNative.requestFastLink(self, peerId, resolver: resolver, rejecter: rejecter) + } + + @objc func closeFastLink(_ peerId: String, + resolver: @escaping RCTPromiseResolveBlock, + rejecter: @escaping RCTPromiseRejectBlock) { + ProtocolEngineHostBridgeReactNative.closeFastLink(self, peerId, resolver: resolver, rejecter: rejecter) + } + // MARK: - User Blocking @objc func blockUser(_ userId: String, diff --git a/bindings/react-native/ios/ProtocolEngineHostBridge.swift b/bindings/react-native/ios/ProtocolEngineHostBridge.swift index 4a84854b2..04d26924b 100644 --- a/bindings/react-native/ios/ProtocolEngineHostBridge.swift +++ b/bindings/react-native/ios/ProtocolEngineHostBridge.swift @@ -118,6 +118,18 @@ enum ProtocolEngineHostBridge { // MARK: - Blocking, files, presence + /// Asks for a fast link to `peerId` (ADR 0038); returns the link id. + static func requestFastLink(host: ProtocolEngineHost, env: EngineBridgeEnvironment, arguments: Any?) throws -> Any? { + let m = try A.map(arguments, for: "requestFastLink") + return try host.requireProtocol().requestFastLink(peerId: try A.requireString(m, "peerId")) + } + + /// Ends the fast link with `peerId`; returns whether there was one. + static func closeFastLink(host: ProtocolEngineHost, env: EngineBridgeEnvironment, arguments: Any?) throws -> Any? { + let m = try A.map(arguments, for: "closeFastLink") + return try host.requireProtocol().closeFastLink(peerId: try A.requireString(m, "peerId")) + } + static func blockUser(host: ProtocolEngineHost, env: EngineBridgeEnvironment, arguments: Any?) throws -> Any? { let m = try A.map(arguments, for: "blockUser") try host.requireProtocol().blockUser(userId: try A.requireString(m, "userId")) diff --git a/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift b/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift index 54c3c36cb..845995028 100644 --- a/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift +++ b/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift @@ -63,6 +63,18 @@ enum ProtocolEngineHostBridgeReactNative { } } + static func requestFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { + run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to request a fast link", mapProtocolErrors: true) { host, env in + try ProtocolEngineHostBridge.requestFastLink(host: host, env: env, arguments: ["peerId": peerId]) + } + } + + static func closeFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { + run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to close the fast link") { host, env in + try ProtocolEngineHostBridge.closeFastLink(host: host, env: env, arguments: ["peerId": peerId]) + } + } + static func blockUser(_ module: OfflineProtocolModule, _ userId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_BLOCK_USER", errorMessage: "Failed to block user") { host, env in try ProtocolEngineHostBridge.blockUser(host: host, env: env, arguments: ["userId": userId]) diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index 525b68617..d5c747878 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4600,6 +4600,42 @@ export class OfflineProtocol { ); } + // ─── Fast link ────────────────────────────────────────────── + + /** + * Brings up a Wi-Fi network between this device and `peerId`, a peer with + * a confirmed session that is reachable over Bluetooth LE (ADR 0038). One + * device hosts (an Android phone) and the other joins, with credentials + * sealed in the session, and traffic moves onto the link by ordinary + * transport selection: a 1 MiB file that takes minutes over Bluetooth takes + * seconds over it. + * + * Resolves with the link id as soon as the first step is taken; the outcome + * arrives as `fast_link_changed` events. On iOS the join shows a system + * prompt and takes the phone off its own Wi-Fi while the link lasts, and + * the link ends when the app leaves the foreground, so ask for it when a + * transfer is worth that. Needs the Hotspot Configuration entitlement on + * iOS and `NEARBY_WIFI_DEVICES` (fine location below Android 13) on Android. + * + * Rejects when the peer has not advertised support, there is no confirmed + * session or live Bluetooth link to it, a peer stream already reaches it, + * this device can neither host nor join, or a link with another peer is + * held. + */ + async requestFastLink(peerId: string): Promise { + warnPeerIdIfMisshapen(peerId, 'requestFastLink'); + return await OfflineProtocolNativeModule.requestFastLink(peerId); + } + + /** + * Ends the fast link with `peerId`, telling the peer. Resolves with whether + * there was one. + */ + async closeFastLink(peerId: string): Promise { + warnPeerIdIfMisshapen(peerId, 'closeFastLink'); + return await OfflineProtocolNativeModule.closeFastLink(peerId); + } + // ─── User Blocking ────────────────────────────────────────── /** diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 7d94cab0f..53f8f30e7 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -19893,7 +19893,9 @@ mod tests { // Joined since, each by decision. The subscription calls (ADR 0035) // map like the request and response they sit beside: an app tells a // provider that does not route subscriptions (`ServiceError`) from a - // generic failure by the typed code. + // generic failure by the typed code. A fast-link request (ADR 0038) + // maps for the same reason: its refusals (no session, no capability, + // busy) are what an app shows its user. const JOINED_SINCE: &[&str] = &[ "acceptServiceSubscription", "clearServiceTopic", @@ -19907,6 +19909,7 @@ mod tests { "setServiceTopicCheckpoint", "subscribeService", "unsubscribeService", + "requestFastLink", ]; let mut expected: Vec<&str> = MAPPED_BEFORE_THE_SHARED_BRIDGE .iter() @@ -20233,12 +20236,17 @@ mod tests { let code = rn_source_code_only("android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt"); for (what, pinned) in [ + // The same wake carries the fast link's directives (ADR 0038). Both + // calls only post to the manager's thread, so the callback still + // returns at once; the second exists because the body drain stops + // at "no stream yet", and a directive is what brings one up. ( "the registration, gated on the slot", "if (currentConfig?.wifiDirectEnabled == true) { try { \ proto.setWifiDirectTransportCallback(object : \ uniffi.offline_protocol.WifiDirectTransportCallback { override fun \ - onMessagesAvailable() { wifiDirectManager?.onMessagesAvailable() } })", + onMessagesAvailable() { wifiDirectManager?.onMessagesAvailable() \ + wifiDirectManager?.onFastLinkWake() } })", ), ( "the field the callback reads", diff --git a/tools/gen_engine_method_handlers.py b/tools/gen_engine_method_handlers.py index 8186411bf..44ec7fd70 100644 --- a/tools/gen_engine_method_handlers.py +++ b/tools/gen_engine_method_handlers.py @@ -264,6 +264,7 @@ def fn(name: str, body: str) -> str: "cancelConnectionRequest", "cancelFileTransfer", "checkInternetPresence", + "closeFastLink", "createInvite", "deriveAddress", "deriveUserIdFromPublicKey", @@ -333,6 +334,7 @@ def fn(name: str, body: str) -> str: "rekeySession", "releaseTransportLock", "requestEnableBluetooth", + "requestFastLink", "resolveUsername", "respondToServiceRequest", "sendConnectionRequest", diff --git a/tools/gen_protocol_engine_host_bridge.py b/tools/gen_protocol_engine_host_bridge.py index 3b3808934..f5ab30cb2 100644 --- a/tools/gen_protocol_engine_host_bridge.py +++ b/tools/gen_protocol_engine_host_bridge.py @@ -20,6 +20,7 @@ "cancelFileTransfer", "checkInternetPresence", "clearServiceTopic", + "closeFastLink", "createInvite", "deriveAddress", "deriveUserIdFromPublicKey", @@ -91,6 +92,7 @@ "rekeySession", "releaseTransportLock", "requestEnableBluetooth", + "requestFastLink", "resolveUsername", "respondToServiceRequest", "resyncServiceSubscription", @@ -448,6 +450,22 @@ } """ +IMPL["requestFastLink"] = """ + /** Asks for a fast link to `peerId` (ADR 0038); returns the link id. */ + fun requestFastLink(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { + val map = mapFromAny(arguments) + return host.requireProtocolBridge().requestFastLink(requireString(map, "peerId")) + } +""" + +IMPL["closeFastLink"] = """ + /** Ends the fast link with `peerId`; returns whether there was one. */ + fun closeFastLink(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { + val map = mapFromAny(arguments) + return host.requireProtocolBridge().closeFastLink(requireString(map, "peerId")) + } +""" + IMPL["cancelConnectionRequest"] = """ fun cancelConnectionRequest(host: ProtocolEngineHost, ctx: Context?, arguments: Any?): Any? { val map = mapFromAny(arguments) diff --git a/tools/rn_engine_bridge_error_manifest.json b/tools/rn_engine_bridge_error_manifest.json index 5ef27e47f..d5a848d54 100644 --- a/tools/rn_engine_bridge_error_manifest.json +++ b/tools/rn_engine_bridge_error_manifest.json @@ -40,6 +40,10 @@ "mapProtocolErrors": true, "message": "Failed to clear service topic" }, + "closeFastLink": { + "code": "ERROR_FAST_LINK", + "message": "Failed to close the fast link" + }, "createInvite": { "code": "ERROR_NOT_INITIALIZED", "message": "Protocol not initialized" @@ -333,6 +337,11 @@ "code": "ERROR_BLUETOOTH", "message": "Bluetooth not available on this device" }, + "requestFastLink": { + "code": "ERROR_FAST_LINK", + "mapProtocolErrors": true, + "message": "Failed to request a fast link" + }, "resolveUsername": { "code": "ERROR_INVALID_ARGUMENT", "mapProtocolErrors": true, From 9029f49e0a22146964ad16ac826f28c38d88af24 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 06:24:43 +0530 Subject: [PATCH 09/81] feat(bindings): join a fast link on ios the ios manager declares it can join and not host, and drains the engine's directives on the transport callback, off the core's mutex. a join applies a joinonce hotspot configuration, reports a declined prompt as declined, and dials the offered address and port bound to wi-fi with the host as its claim, again every two seconds until the stream proves the host or the offer runs out. backgrounding leaves the network and tells the engine at once, because ios drops it 15 s later anyway and the host would otherwise wait on keepalive. the phase 1 spike is gone. --- .../react-native/ios/WifiDirectManager.swift | 273 +++++++++++------- 1 file changed, 167 insertions(+), 106 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 7b5dce8c1..2aeef27a9 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -10,11 +10,10 @@ import Foundation import Network -import os.log -// SPIKE(fast-link): scoped, because the module also exports a legacy NWEndpoint. +// Scoped: NetworkExtension also exports a legacy `NWEndpoint`, which would make +// every use of Network's ambiguous in this file. import class NetworkExtension.NEHotspotConfiguration import class NetworkExtension.NEHotspotConfigurationManager -import class NetworkExtension.NEHotspotNetwork /// The engine's peer-stream slot on iOS, over `NWListener`, `NWBrowser` and /// `NWConnection`. @@ -170,6 +169,8 @@ public class WifiDirectManager: NSObject, TransportManager { /// Bumped by every start() and stop(), so a timer armed for one run finds /// nothing to act on in the next. private var generation = 0 + /// The fast link this device is joining or has joined, if any. + private var fastLink: FastLinkJoin? /// Guards [_state] and [_isPaused], which the lifecycle writes from the /// bridge queue and the send path reads from any thread. Everything @@ -290,7 +291,8 @@ public class WifiDirectManager: NSObject, TransportManager { updateState(.running) try? protocolInstance.wifiDirectStatusChanged(isConnected: true) emitDiagnostic("info", "Peer-stream transport started") - spikeJoinIfConfigured() + // An iPhone joins a fast link and cannot host one (ADR 0038). + try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: true) } public func stop() { @@ -326,6 +328,8 @@ public class WifiDirectManager: NSObject, TransportManager { } try? protocolInstance.wifiDirectStatusChanged(isConnected: false) + try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false) + onLinkQueueSync { endFastLink(reason: "failed") } updateState(.stopped) emitDiagnostic("info", "Peer-stream transport stopped") @@ -336,7 +340,14 @@ public class WifiDirectManager: NSObject, TransportManager { // path, see `isPaused`; stopping the browser only stops finding new // peers. The listener stays up, so a peer can still reach us. isPaused = true - onLinkQueueSync { stopBrowsing() } + onLinkQueueSync { + stopBrowsing() + // iOS drops a joined network 15 s after the app leaves the + // foreground and deletes its passphrase. Leaving now, and saying + // so, lets the host end its half at once rather than when + // keepalive notices, about 40 s later. + endFastLink(reason: "background") + } } public func resume() { @@ -357,6 +368,9 @@ public class WifiDirectManager: NSObject, TransportManager { /// available. Goes straight to the drain: `state` and the proved peers are /// both readable from any thread. public func onMessagesAvailable() { + // The same wake carries fast-link directives (ADR 0038). Async: the + // core calls this holding its mutex, and draining a directive takes it. + linkQueue.async { [weak self] in self?.drainFastLinkDirectives() } drainAndSendMessages() } @@ -799,7 +813,6 @@ extension WifiDirectManager: PeerStreamHost { "error": error.localizedDescription ]) } - spikeLog("peer stream proved \(address)") } func peerStreamReceived(_ address: String, _ body: Data) { @@ -833,112 +846,160 @@ extension WifiDirectManager: PeerStreamHost { extension WifiDirectManager: @unchecked Sendable {} -// MARK: - SPIKE (BLE-to-Wi-Fi fast link, phase 1). Throwaway: not a design. -// -// Driven from the Mac, so the spike needs no UDL or JS surface. Copy a JSON -// file into the app's container: -// -// {"ssid":"DIRECT-sp-...","pass":"","host":"192.168.49.1"} -// xcrun devicectl device copy to --device \ -// --domain-type appDataContainer --domain-identifier \ -// --source opspike.json --destination Documents/opspike.json -// -// Optional keys: port (default 8988), joinOnce (default true), addr (the -// address the preamble must prove). Launch arguments (-opSpikeSSID and so on) -// work too, but iOS relaunches the app for Bluetooth restoration without them. -// The join runs when this transport starts. Logs go to os_log as "OPSPIKE". +// MARK: - Fast link (ADR 0038) + +/// A network this device joins for one peer, from an offer that arrived +/// sealed in their session. linkQueue only. +private final class FastLinkJoin { + let linkId: String + let peer: String + let ssid: String + let host: String + let port: UInt16 + /// When the engine gives up on it; no dial after this. + let deadline: TimeInterval + /// iOS reported the join. + var joined = false + /// The stream dialed toward the host for this link. + weak var stream: AnyObject? + + init(linkId: String, peer: String, ssid: String, host: String, port: UInt16, deadline: TimeInterval) { + self.linkId = linkId + self.peer = peer + self.ssid = ssid + self.host = host + self.port = port + self.deadline = deadline + } +} + +/// An iPhone joins a fast link (ADR 0038) and never hosts one: iOS cannot +/// open an access point from code. The network is joined with +/// `NEHotspotConfiguration` and `joinOnce`, which shows the user a prompt +/// every time and leaves the network when the app leaves the foreground; the +/// stream is dialed to the address and port the offer named, claiming the +/// host, so a preamble proving anyone else closes it. The passphrase is +/// never logged. extension WifiDirectManager { - private static var spikeT0: TimeInterval = 0 - private static let spikeOSLog = OSLog(subsystem: "com.offlineprotocol.spike", category: "OPSPIKE") - - func spikeLog(_ message: String) { - let now = ProcessInfo.processInfo.systemUptime - let since = Self.spikeT0 == 0 ? 0 : Int((now - Self.spikeT0) * 1000) - let line = "OPSPIKE wall=\(Int64(Date().timeIntervalSince1970 * 1000)) +\(since)ms \(message)" - os_log("%{public}@", log: Self.spikeOSLog, type: .default, line) - } - - fileprivate func spikeJoinIfConfigured() { - // Documents/opspike.json, copied in with `devicectl device copy to`, - // wins over launch arguments: iOS relaunches the app for Bluetooth - // restoration, and a relaunch carries no arguments. - var config: [String: Any] = [:] - if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first, - let data = try? Data(contentsOf: dir.appendingPathComponent("opspike.json")), - let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { - config = object - } else { - let defaults = UserDefaults.standard - for key in ["ssid": "opSpikeSSID", "pass": "opSpikePass", "host": "opSpikeHost", "addr": "opSpikeAddr"] { - if let value = defaults.string(forKey: key.value) { config[key.key] = value } + /// Gives a dial this long to become ready before it is tried again. + private static let FAST_LINK_REDIAL: TimeInterval = 2.0 + /// `NEHotspotConfigurationError.userDenied`. + private static let HOTSPOT_USER_DENIED = 7 + /// `NEHotspotConfigurationError.alreadyAssociated`: the join holds. + private static let HOTSPOT_ALREADY_ASSOCIATED = 13 + + /// Runs what the engine asked for. linkQueue only. + fileprivate func drainFastLinkDirectives() { + guard state == .running else { return } + while let directive = protocolInstance.wifiDirectNextFastLinkDirective() { + switch directive.kind { + case "join": + joinFastLink(directive) + case "close": + if fastLink?.linkId == directive.linkId { endFastLink(reason: nil) } + default: + // "host": this device declared it cannot. + protocolInstance.wifiDirectFastLinkEnded(linkId: directive.linkId, reason: "host_failed") } - if defaults.integer(forKey: "opSpikePort") != 0 { config["port"] = defaults.integer(forKey: "opSpikePort") } - if defaults.object(forKey: "opSpikeJoinOnce") != nil { config["joinOnce"] = defaults.bool(forKey: "opSpikeJoinOnce") } - } - spikeLog("transport started; spike config ssid=\(config["ssid"] as? String ?? "nil")") - guard let ssid = config["ssid"] as? String, - let pass = config["pass"] as? String, - let host = config["host"] as? String else { return } - let port = config["port"] as? Int ?? 0 - let joinOnce = config["joinOnce"] as? Bool ?? true - let expected = config["addr"] as? String - Self.spikeT0 = ProcessInfo.processInfo.systemUptime - spikeLog("apply ssid=\(ssid) joinOnce=\(joinOnce) host=\(host):\(port == 0 ? 8988 : port)") - let configuration = NEHotspotConfiguration(ssid: ssid, passphrase: pass, isWEP: false) - configuration.joinOnce = joinOnce + } + } + + private func joinFastLink(_ directive: FastLinkDirective) { + guard fastLink == nil, + let ssid = directive.ssid, + let passphrase = directive.passphrase, + let host = directive.host, + let port = directive.port else { + protocolInstance.wifiDirectFastLinkEnded(linkId: directive.linkId, reason: "failed") + return + } + let link = FastLinkJoin( + linkId: directive.linkId, + peer: directive.peerId, + ssid: ssid, + host: host, + port: port, + deadline: ProcessInfo.processInfo.systemUptime + TimeInterval(directive.expiresInMs) / 1000 + ) + fastLink = link + emitDiagnostic("info", "Fast link: joining a network", context: ["linkId": link.linkId]) + let configuration = NEHotspotConfiguration(ssid: ssid, passphrase: passphrase, isWEP: false) + configuration.joinOnce = true NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] error in - guard let self = self else { return } - if let error = error as NSError? { - self.spikeLog("apply finished error domain=\(error.domain) code=\(error.code) \(error.localizedDescription)") - // alreadyAssociated (13) is a join that already holds. - if error.code != 13 { return } - } else { - self.spikeLog("apply finished ok") - } - NEHotspotNetwork.fetchCurrent { network in - self.spikeLog("current network ssid=\(network?.ssid ?? "nil") bssid=\(network?.bssid ?? "nil")") - } - self.spikeDial(host: host, port: port == 0 ? 8988 : port, expected: expected, attempt: 1) + self?.linkQueue.async { self?.fastLinkJoinFinished(link, error: error as NSError?) } } } - /// Dials the host's listener directly: there is no DNS-SD on the group. - /// Retried each second until a stream proves its peer, for 30 attempts. - private func spikeDial(host: String, port: Int, expected: String?, attempt: Int) { - linkQueue.async { [weak self] in - guard let self = self, self.state == .running else { return } - if !self.peers.isEmpty, let expected = expected, self.peers.handle(for: expected) != nil { - self.spikeLog("already proved \(expected); not dialing") - return - } - self.spikeLog("dial attempt \(attempt) to \(host):\(port)") - let endpoint = NWEndpoint.hostPort( - host: NWEndpoint.Host(host), port: NWEndpoint.Port(integerLiteral: UInt16(port))) - let parameters = Self.makeParameters() - parameters.requiredInterfaceType = .wifi - let stream = Stream( - connection: NWConnection(to: endpoint, using: parameters), - outbound: true, - dialed: nil - ) - self.peers.claim(expected, for: stream) - self.open(stream) - // Wrapped after open(): both run on linkQueue, so no state change - // is delivered in between. - let handler = stream.connection.stateUpdateHandler - stream.connection.stateUpdateHandler = { [weak self, weak stream] state in - let local = stream?.connection.currentPath?.localEndpoint - self?.spikeLog("dial \(attempt) state \(state) local=\(String(describing: local))") - handler?(state) - } - self.linkQueue.asyncAfter(deadline: .now() + 3) { [weak self] in - guard let self = self else { return } - if self.peers.provedAddress(of: stream) != nil { return } - if attempt >= 30 { self.spikeLog("giving up"); return } - if case .ready = stream.connection.state { return } - stream.connection.cancel() - self.spikeDial(host: host, port: port, expected: expected, attempt: attempt + 1) - } + private func fastLinkJoinFinished(_ link: FastLinkJoin, error: NSError?) { + guard fastLink === link else { + // Closed while the user read the prompt: leave what was joined. + NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: link.ssid) + return + } + if let error = error, error.code != Self.HOTSPOT_ALREADY_ASSOCIATED { + let reason = error.code == Self.HOTSPOT_USER_DENIED ? "declined" : "failed" + emitDiagnostic("warning", "Fast link: the join did not happen", context: [ + "linkId": link.linkId, + "reason": reason, + "code": error.code, + ]) + fastLink = nil + NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: link.ssid) + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: reason) + return + } + link.joined = true + dialFastLink(link) + } + + /// Dials the host's listener, bound to Wi-Fi, claiming the host. There is + /// no discovery record on the network: the offer named the address. A + /// dial that ends without proving the host is tried again until the + /// engine's deadline, since the first one often races the address + /// arriving over DHCP. + private func dialFastLink(_ link: FastLinkJoin) { + guard fastLink === link, link.joined, state == .running, + ProcessInfo.processInfo.systemUptime < link.deadline else { return } + if let held = peers.handle(for: link.peer), streams.contains(held) { return } + if let current = link.stream as? Stream, streams.contains(current) { + // Still connecting (waiting on the path, or mid-preamble). + scheduleFastLinkRedial(link) + return + } + guard streams.count < Self.MAX_STREAMS, + let port = NWEndpoint.Port(rawValue: link.port) else { return } + let parameters = Self.makeParameters() + parameters.requiredInterfaceType = .wifi + let stream = Stream( + connection: NWConnection( + to: .hostPort(host: NWEndpoint.Host(link.host), port: port), + using: parameters + ), + outbound: true, + dialed: nil + ) + peers.claim(link.peer, for: stream) + link.stream = stream + open(stream) + scheduleFastLinkRedial(link) + } + + private func scheduleFastLinkRedial(_ link: FastLinkJoin) { + linkQueue.asyncAfter(deadline: .now() + Self.FAST_LINK_REDIAL) { [weak self] in + self?.dialFastLink(link) + } + } + + /// Leaves the link's network and ends its stream. With a reason, the + /// engine is told (the platform's own end); without one, the engine + /// asked. linkQueue only. + fileprivate func endFastLink(reason: String?) { + guard let link = fastLink else { return } + fastLink = nil + (link.stream as? Stream)?.connection.cancel() + NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: link.ssid) + if let reason = reason { + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: reason) } } } From 4ca42b13a71c19634cc3093327fef466c2252e87 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 06:40:51 +0530 Subject: [PATCH 10/81] fix(protocol): let only large bodies hold a fast link up on two phones the example app's presence update every 15 s kept the link from ever going idle, which kept the iphone off its own wi-fi for as long as the app ran. only a body of at least 16 kib, half a media chunk on the slot, now moves the idle clock; a transfer in flight still holds it as before. --- crates/offline-protocol-uniffi/src/lib.rs | 2 +- crates/offline-protocol/src/fast_link.rs | 35 +++++++++++++++---- .../src/protocol/fast_link.rs | 6 ++-- crates/offline-protocol/src/protocol/send.rs | 7 +++- ...fast-link-is-offered-inside-the-session.md | 4 +-- docs/state-machines/fast-link.md | 11 +++--- 6 files changed, 48 insertions(+), 17 deletions(-) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 53f8f30e7..9d4a4cfbd 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -5419,7 +5419,7 @@ impl OfflineProtocol { ) -> Result<(), ProtocolError> { let mut protocol = self.lock_inner()?; // Traffic on the slot keeps a fast link off its idle limit. - protocol.fast_link_activity(&sender_id); + protocol.fast_link_activity(&sender_id, data.len()); if let Some(transport_arc) = protocol .transport_manager() .get_transport(CoreTransportType::WiFiDirect) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 76d16f06d..711eb03bc 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -43,10 +43,16 @@ pub const HOSTING_TIMEOUT: Duration = Duration::from_secs(20); /// How long a requester waits for an offer. pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); -/// How long an up link may carry nothing, with no transfer to the peer in -/// flight, before it ends. It costs the joiner its own Wi-Fi. +/// How long an up link may carry nothing large, with no transfer to the peer +/// in flight, before it ends. It costs the joiner its own Wi-Fi. pub const IDLE_LIMIT: Duration = Duration::from_secs(60); +/// The smallest body that counts as activity for [`IDLE_LIMIT`]: half a media +/// chunk on the slot. Presence, receipts and chat are smaller and go over +/// Bluetooth LE perfectly well, and counting them kept a link up for as long +/// as an application sent presence every 15 s (two phones, ADR 0038). +pub const ACTIVITY_MIN_BYTES: usize = 16 * 1024; + /// Hex digits in a link id, 128 bits. pub const LINK_ID_HEX_LEN: usize = 32; @@ -796,8 +802,12 @@ impl FastLinks { } } - /// The slot carried a body for `peer`. - pub(crate) fn activity(&mut self, peer: &str, now: Instant) { + /// The slot carried a body of `bytes` for `peer`. Only a large one moves + /// the idle clock ([`ACTIVITY_MIN_BYTES`]). + pub(crate) fn activity(&mut self, peer: &str, bytes: usize, now: Instant) { + if bytes < ACTIVITY_MIN_BYTES { + return; + } if let Some(link) = self.link.as_mut() { if link.peer == peer { link.last_activity = now; @@ -1391,9 +1401,22 @@ mod tests { host.stream_proved(HIGH, t0); host.take_changes(); - host.activity(HIGH, t0 + Duration::from_secs(30)); + host.activity(HIGH, ACTIVITY_MIN_BYTES - 1, t0 + Duration::from_secs(20)); + host.activity(HIGH, ACTIVITY_MIN_BYTES, t0 + Duration::from_secs(30)); + host.activity(HIGH, 300, t0 + Duration::from_secs(80)); host.tick(t0 + IDLE_LIMIT, |_| false); - assert!(host.peer().is_some(), "activity moved the idle clock"); + assert!(host.peer().is_some(), "a large body moved the idle clock"); + host.tick(t0 + Duration::from_secs(30) + IDLE_LIMIT, |_| false); + assert_eq!( + host.take_changes().last().unwrap().reason, + Some(CloseReason::Idle), + "presence-sized chatter does not hold a link up" + ); + + let id = host.request(HIGH, fresh(2), t0).unwrap(); + host.hosting(&id, "192.168.49.1", 8988, t0, 0); + host.stream_proved(HIGH, t0); + host.take_changes(); host.tick(t0 + Duration::from_secs(200), |peer| peer == HIGH); assert!(host.peer().is_some(), "a transfer in flight is not idle"); diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 2e363a204..accf98e4a 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -130,9 +130,9 @@ impl OfflineProtocol { self.flush_fast_link(); } - /// The peer-stream slot carried a body for `peer`. - pub fn fast_link_activity(&mut self, peer: &str) { - self.fast_links.activity(peer, Instant::now()); + /// The peer-stream slot carried a body of `bytes` for `peer`. + pub fn fast_link_activity(&mut self, peer: &str, bytes: usize) { + self.fast_links.activity(peer, bytes, Instant::now()); } /// A fast-link frame decrypted in the 1:1 session with `sender`, who is diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index 92224a094..0360df698 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -4269,7 +4269,12 @@ impl OfflineProtocol { // limit (ADR 0038). Inbound traffic is noted where the platform hands // a body up. if transport == Some(TransportType::WiFiDirect) { - self.fast_link_activity(message.recipient.as_str()); + let bytes = message.content.len() + + message + .binary_content + .as_ref() + .map_or(0, |bytes| bytes.len()); + self.fast_link_activity(message.recipient.as_str(), bytes); } // Never `?`: the frame is already on the wire, so an error here would // report a transmitted message as failed. Every transmit path asks diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index faf943c28..2c991d183 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -88,8 +88,8 @@ the foreground and deleted the passphrase. off the network just joined. 7. **The engine ends a link** when its offer expires unused (120 s), when the - proved stream is lost, after 60 s with nothing carried and no transfer to - the peer under way, on either side's `close`, and on the application's + proved stream is lost, after 60 s with nothing large carried (a body of + 16 KiB or more) and no transfer to the peer under way, on either side's `close`, and on the application's `close_fast_link`. A joiner's platform reports its own end when it can no longer hold the network: iOS does when the application leaves the foreground, because iOS disconnects 15 s later anyway and the host would diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index a29615e02..75c017c19 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -101,10 +101,13 @@ for this device's platform when the platform holds anything for the link, a come from the peer, and one `fast_link_changed` event with state `closed` and the reason. -The idle limit counts a body carried by the slot in either direction for this -peer as activity, and does not run while a file transfer to the peer is in -flight. A link that carries nothing for 60 s is costing the user their own -Wi-Fi for no reason. +The idle limit counts a body of at least 16 KiB carried by the slot in either +direction for this peer as activity, and does not run while a file transfer +to the peer is in flight. Smaller bodies (presence, receipts, chat) do not +count: Bluetooth LE carries them well, and on two phones an application's +presence update every 15 s held a link up indefinitely when they did. A link +that carries nothing large for 60 s is costing the user their own Wi-Fi for +no reason. A joiner's platform that is about to lose the network reports it as `ended` first: on iOS, leaving the foreground, after which iOS disconnects at 15 s From 740a760e9fca22052b12b4337f6ccc0da78fc9a6 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:15:08 +0530 Subject: [PATCH 11/81] fix(protocol): carry fast-link frames over bluetooth and refuse late ones two bugs found on the phones with an iphone-initiated link. the engine sends a direct frame down the peer stream when it holds one, so a close went down the stream it was ending and reached the iphone 22 s late, and a request went down a lan stream the iphone had just left and reached the android 63 s late. fast-link frames now go over bluetooth le whenever the peer is linked there. and that late request was hosted, and its offer prompted the iphone's user to join a network the android had already removed: a device now remembers the links it ended for ten minutes, drops a late request for one, and answers a late offer with close expired so the host takes it down. --- crates/offline-protocol/src/fast_link.rs | 151 ++++++++++++++++-- .../src/protocol/fast_link.rs | 24 ++- .../src/protocol/tests/fast_link.rs | 44 +++++ docs/spec/control-messages.md | 5 +- docs/state-machines/fast-link.md | 11 +- 5 files changed, 212 insertions(+), 23 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 711eb03bc..1a6f8e50d 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -59,6 +59,14 @@ pub const LINK_ID_HEX_LEN: usize = 32; /// Hex digits in a passphrase the engine makes, 128 bits. pub const PASSPHRASE_HEX_LEN: usize = 32; +/// How long an ended link's id is remembered, so a frame for it that arrives +/// late is refused rather than acted on: the longest an offer lives, plus +/// the clock slack. +pub const ENDED_MEMORY: Duration = Duration::from_millis(MAX_OFFER_TTL_MS + 300_000); + +/// How many ended link ids are remembered. One link at a time, so a few. +pub const MAX_ENDED_REMEMBERED: usize = 16; + /// The largest body after the prefix a receiver parses. An offer is about /// 250 bytes. pub const MAX_FRAME_BODY_BYTES: usize = 2048; @@ -476,6 +484,12 @@ pub(crate) struct FastLinks { directives: VecDeque, frames: VecDeque<(String, Frame)>, changes: VecDeque, + /// Links this device ended, and when. A request or offer for one that + /// arrives afterwards is late, and acting on it would bring up or join a + /// network nobody is waiting for: on two phones a request delayed 63 s + /// reached the host after the requester had given up, and its offer then + /// prompted the requester's user to join a network already removed. + ended: VecDeque<(String, Instant)>, } impl FastLinks { @@ -578,7 +592,7 @@ impl FastLinks { return false; } if !is_local_host(host) || port == 0 { - self.end(CloseReason::HostFailed, true); + self.end(CloseReason::HostFailed, true, now); return false; } let Some(link) = self.link.as_mut() else { @@ -616,6 +630,14 @@ impl FastLinks { now: Instant, now_ms: i64, ) { + if self.ended_recently(&frame.link, now) { + // A late request needs no answer: its sender has given up on it. + // A late offer gets one, so the host takes its network down. + if matches!(frame.body, FrameBody::Offer(_)) { + self.reply_close(peer, &frame.link, CloseReason::Expired); + } + return; + } match frame.body { FrameBody::Request => self.on_request(peer, &frame.link, fresh, now), FrameBody::Offer(offer) => self.on_offer(peer, local, &frame.link, offer, now, now_ms), @@ -625,7 +647,7 @@ impl FastLinks { .as_ref() .is_some_and(|link| link.id == frame.link && link.peer == peer) { - self.end(CloseReason::parse(&reason), false); + self.end(CloseReason::parse(&reason), false, now); } } } @@ -701,7 +723,7 @@ impl FastLinks { if local.as_bytes() < peer.as_bytes() { return; } - self.end(CloseReason::Busy, true); + self.end(CloseReason::Busy, true, now); } FastLinkRole::Join => { if link.id == link_id && link.state != FastLinkState::Requested { @@ -711,7 +733,7 @@ impl FastLinks { if link.state != FastLinkState::Requested { // A new offer replaces the one before it: the host // brought up a new network. Nothing to tell it. - self.end(CloseReason::Failed, false); + self.end(CloseReason::Failed, false, now); } else { // The offer answers our request; it supersedes the // request's link quietly, whatever id the host chose. @@ -756,11 +778,16 @@ impl FastLinks { /// The platform could not do what it was told, or can no longer hold the /// link. It already let go, so no `close` directive follows. - pub(crate) fn platform_ended(&mut self, link_id: &str, reason: CloseReason) -> bool { + pub(crate) fn platform_ended( + &mut self, + link_id: &str, + reason: CloseReason, + now: Instant, + ) -> bool { match self.link.as_mut() { Some(link) if link.id == link_id => { link.platform_engaged = false; - self.end(reason, true); + self.end(reason, true, now); true } _ => false, @@ -768,11 +795,11 @@ impl FastLinks { } /// The application ends the link with `peer`. - pub(crate) fn close(&mut self, peer: &str) -> bool { + pub(crate) fn close(&mut self, peer: &str, now: Instant) -> bool { if self.peer() != Some(peer) { return false; } - self.end(CloseReason::Closed, true); + self.end(CloseReason::Closed, true, now); true } @@ -792,13 +819,13 @@ impl FastLinks { } /// The stream that proved `peer` ended. - pub(crate) fn stream_lost(&mut self, peer: &str) { + pub(crate) fn stream_lost(&mut self, peer: &str, now: Instant) { if self .link .as_ref() .is_some_and(|link| link.peer == peer && link.state == FastLinkState::Up) { - self.end(CloseReason::Lost, true); + self.end(CloseReason::Lost, true, now); } } @@ -839,17 +866,32 @@ impl FastLinks { _ => None, }; if let Some(reason) = reason { - self.end(reason, true); + self.end(reason, true, now); } } + fn ended_recently(&mut self, link_id: &str, now: Instant) -> bool { + while self + .ended + .front() + .is_some_and(|(_, at)| now.saturating_duration_since(*at) >= ENDED_MEMORY) + { + self.ended.pop_front(); + } + self.ended.iter().any(|(id, _)| id == link_id) + } + /// Ends the link: a `close` directive when the platform holds something, /// a `close` frame when the peer knows of it and `tell_peer`, and one /// change (invariant 4). - fn end(&mut self, reason: CloseReason, tell_peer: bool) { + fn end(&mut self, reason: CloseReason, tell_peer: bool, now: Instant) { let Some(link) = self.link.take() else { return; }; + if self.ended.len() >= MAX_ENDED_REMEMBERED { + self.ended.pop_front(); + } + self.ended.push_back((link.id.clone(), now)); if link.platform_engaged { self.directives.push_back(PendingDirective { directive: FastLinkDirective { @@ -1276,7 +1318,7 @@ mod tests { android.stream_proved(HIGH, t0); android.take_changes(); - android.stream_lost(HIGH); + android.stream_lost(HIGH, t0); let close = android.next_directive(t0).unwrap(); assert_eq!(close.kind, FastLinkDirectiveKind::Close); assert_eq!(close.reason, Some(CloseReason::Lost)); @@ -1349,7 +1391,7 @@ mod tests { 0, ); iphone.next_directive(t0); - assert!(iphone.platform_ended(&id, CloseReason::Declined)); + assert!(iphone.platform_ended(&id, CloseReason::Declined, t0)); assert!(!iphone.has_directives()); let frames = iphone.take_frames(); assert_eq!( @@ -1460,6 +1502,87 @@ mod tests { assert!(android.next_directive(t0).is_none(), "one network, not two"); } + #[test] + fn a_late_offer_for_a_link_given_up_on_is_refused_not_joined() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let id = iphone.request(LOW, fresh(1), t0).unwrap(); + let request = iphone.take_frames(); + iphone.tick(t0 + REQUEST_TIMEOUT, |_| false); + iphone.take_frames(); + iphone.take_changes(); + + // The request arrives after the requester gave up, and is hosted. + for (_, frame) in request { + android.on_frame(HIGH, LOW, frame, fresh(2), t0 + REQUEST_TIMEOUT, 0); + } + android.next_directive(t0); + assert!(android.hosting(&id, "192.168.49.1", 8988, t0 + REQUEST_TIMEOUT, 0)); + let late = REQUEST_TIMEOUT + Duration::from_secs(1); + deliver(&mut android, LOW, &mut iphone, HIGH, t0 + late, 0); + + assert!( + !iphone.has_directives(), + "the user was prompted for a link nobody waits on" + ); + assert!(iphone.take_changes().is_empty()); + let answer = iphone.take_frames(); + assert_eq!(answer.len(), 1); + assert_eq!( + answer[0].1.body, + FrameBody::Close { + reason: "expired".to_string() + } + ); + // The answer takes the host's network down. + for (_, frame) in answer { + android.on_frame(HIGH, LOW, frame, fresh(3), t0 + late, 0); + } + assert_eq!( + android.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Close + ); + + // Remembered for a while, then forgotten. + assert!(iphone.ended_recently( + &id, + t0 + REQUEST_TIMEOUT + ENDED_MEMORY - Duration::from_secs(1) + )); + assert!(!iphone.ended_recently(&id, t0 + REQUEST_TIMEOUT + ENDED_MEMORY)); + } + + #[test] + fn a_late_request_for_an_ended_link_is_not_hosted_again() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let id = fresh(1).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(2), + t0, + 0, + ); + android.next_directive(t0); + android.tick(t0 + HOSTING_TIMEOUT, |_| false); + android.next_directive(t0); + android.take_frames(); + + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(3), + t0 + HOSTING_TIMEOUT, + 0, + ); + assert!(!android.has_directives()); + assert!(android.take_frames().is_empty()); + assert!(android.peer().is_none()); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index accf98e4a..abd7393ef 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -78,7 +78,7 @@ impl OfflineProtocol { /// Ends the fast link with `peer`, if there is one. Returns whether there /// was. pub fn close_fast_link(&mut self, peer: &str) -> bool { - let closed = self.fast_links.close(peer); + let closed = self.fast_links.close(peer, Instant::now()); self.flush_fast_link(); closed } @@ -114,7 +114,7 @@ impl OfflineProtocol { /// link (`reason`: `declined`, `failed`, `host_failed`, `background`, ...). pub fn fast_link_ended(&mut self, link_id: &str, reason: &str) { self.fast_links - .platform_ended(link_id, CloseReason::parse(reason)); + .platform_ended(link_id, CloseReason::parse(reason), Instant::now()); self.flush_fast_link(); } @@ -126,7 +126,7 @@ impl OfflineProtocol { /// The peer stream that proved `peer` ended. pub fn fast_link_stream_lost(&mut self, peer: &str) { - self.fast_links.stream_lost(peer); + self.fast_links.stream_lost(peer, Instant::now()); self.flush_fast_link(); } @@ -206,12 +206,24 @@ impl OfflineProtocol { } } - /// Sealed with the strict encryptor and sent once over the live direct - /// link, with no acknowledgement, outbox or retry (ADR 0032). Fails + /// Sealed with the strict encryptor and sent once over a live direct + /// link, Bluetooth LE first, with no acknowledgement, outbox or retry (ADR 0032). Fails /// before encrypting when there is no link, so no ratchet generation is /// spent on a frame that cannot leave. fn send_fast_link_frame(&mut self, peer: &str, content: &str) -> Result<()> { - let transport = self.direct_link_to(peer)?; + // Bluetooth when the peer is linked there: the link this frame + // starts, stops or replaces may be the peer stream itself, and a + // close sent down a stream being torn down, or a request down a LAN + // stream the peer has just left, arrived 22 to 63 s late on two + // phones, or not at all. + let transport = if self + .transport_manager + .holds_mesh_link(TransportType::BLE, peer) + { + TransportType::BLE + } else { + self.direct_link_to(peer)? + }; let sealed = self.encrypt_content_for_recipient_strict(peer, content)?; let mut message = self.create_message(peer, sealed, Some(MessagePriority::High), None)?; message.requires_ack = false; diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index dab06cd5b..ad7c9e573 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -306,3 +306,47 @@ fn a_transfer_on_the_peer_stream_slot_fills_a_window_of_sixteen() { assert_eq!(chunks, MEDIA_WINDOW_SIZE_PEER_STREAM); assert_eq!(MEDIA_WINDOW_SIZE_PEER_STREAM, 16); } + +/// A fast-link frame goes over Bluetooth LE when the peer is linked there, +/// even though the engine prefers a peer stream for a direct link: the frame +/// may be ending that very stream, and on two phones a close sent down it +/// arrived 22 s late. +#[test] +fn fast_link_frames_prefer_bluetooth_over_the_peer_stream() { + use offline_protocol_transport::PeerLink; + + let (mut alice, mut bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + // A peer stream to bob comes up before the offer leaves: a LAN one, say, + // or the engine's own preference would carry the frame down it. + let stream = MockTransport::new(TransportType::WiFiDirect); + stream.start().unwrap(); + stream.set_connected_peers(vec![PeerLink::new(bob.address.clone())]); + alice + .protocol + .transport_manager_mut() + .add_transport(TransportType::WiFiDirect, Box::new(stream.clone())); + assert_eq!( + alice + .protocol + .transport_manager() + .mesh_transport_for(&bob.address), + Some(TransportType::WiFiDirect), + "the engine prefers the stream for a direct link" + ); + + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + let over_bluetooth = alice.take_sent(); + assert_eq!(over_bluetooth.len(), 1, "the offer went over Bluetooth"); + let over_stream = stream + .sent_messages() + .into_iter() + .chain(stream.peer_sends().into_iter().map(|(_, message)| message)) + .count(); + assert_eq!(over_stream, 0, "nothing went down the peer stream"); + bob.deliver(over_bluetooth); + assert!(bob.protocol.next_fast_link_directive().is_some()); +} diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index 70bd64257..6ed1a4421 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -493,8 +493,9 @@ Four rules hold for every frame of the family: Found anywhere else (a bare frame on the wire, a group plaintext) it is consumed and never surfaced. The body carries a passphrase, and that is the only way it reaches nobody else. -- **Ephemeral.** It is sent once, over a live direct link, with - `requires_ack` false ([ADR 0032](../adr/0032-ephemeral-sends-go-once-over-a-live-link.md)). +- **Ephemeral.** It is sent once, over a live direct link (Bluetooth LE + whenever the peer is linked there, since the frame may be ending the peer + stream itself), with `requires_ack` false ([ADR 0032](../adr/0032-ephemeral-sends-go-once-over-a-live-link.md)). A frame that cannot leave now is not sent. Nothing in the family is ever answered by an acknowledgement, queued, relayed or deposited with a custodian. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 75c017c19..a1baebcc1 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -12,7 +12,8 @@ what each shape prevents. 1. **Credentials leave a device only inside the confirmed 1:1 session with the peer they are for.** A fast-link frame is sealed or not sent, travels once - over a live direct link, and never enters the outbox, a relay or a + over a live direct link (Bluetooth LE whenever the peer is linked there, + never down the stream the frame may be ending), and never enters the outbox, a relay or a neighbour's custody. A frame that arrives in plaintext is never routed here. 2. **A link never announces a peer.** Only a stream's preamble does, exactly as on every other network. The joiner's stream is opened with the host's @@ -85,6 +86,14 @@ ignores the higher one's offer, which its owner is about to withdraw. **A `close` arrives.** It ends the link with that id, if there is one, and is never answered. +**A frame arrives for a link this device ended** within the last ten +minutes (the longest an offer lives, plus the clock slack). It is late. A +request is dropped; an offer is answered `close` (`expired`), so the host +takes its network down, and is never joined. On two phones a request +delayed 63 s reached the host after the requester had given up, and before +this rule its offer prompted the requester's user to join a network that had +already been removed. + An offer is valid when its name is 1 to 32 bytes, its passphrase 8 to 63 printable ASCII characters, its host a private or link-local IP literal, its port not zero, its lifetime at most 300 s, and the time it states it was made no From ebe61c28facf2c3634539daa8bd846762e662eef Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:27:34 +0530 Subject: [PATCH 12/81] fix(protocol): withdraw a fast-link directive the platform never took a link that ended while its platform was paused left its host or join directive in the queue, and the platform ran it on resume: android brought up a group for a dead link, and an iphone would prompt for a network already gone. the machine now counts the platform as holding a link only once it drains the link's directive, withdraws an untaken one when the link ends, and skips a host or join whose time ran out. --- crates/offline-protocol/src/fast_link.rs | 75 ++++++++++++++++++++++-- docs/state-machines/fast-link.md | 4 +- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 1a6f8e50d..d2689b417 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -469,8 +469,10 @@ struct Link { credentials: Option<(String, String)>, /// The host's offer, kept to answer a repeated request. offer: Option, - /// The platform holds something for this link, so its end needs a - /// `close` directive. + /// The platform drained a directive for this link, so its end needs a + /// `close` directive. Set when the platform takes it, not when it is + /// queued: a link that ends before then has its directive withdrawn and + /// owes the platform nothing. platform_engaged: bool, /// The peer knows of this link, so its end needs a `close` frame. peer_engaged: bool, @@ -567,7 +569,7 @@ impl FastLinks { last_activity: now, credentials: Some((fresh.ssid, fresh.passphrase)), offer: None, - platform_engaged: true, + platform_engaged: false, peer_engaged, }); self.changed(None); @@ -770,7 +772,7 @@ impl FastLinks { last_activity: now, credentials: None, offer: None, - platform_engaged: true, + platform_engaged: false, peer_engaged: true, }); self.changed(None); @@ -888,6 +890,11 @@ impl FastLinks { let Some(link) = self.link.take() else { return; }; + // A directive the platform never took is withdrawn: handed out after + // the link ended it would bring up a network nobody waits on, or put + // a join prompt in front of the user for one already gone. + self.directives + .retain(|pending| pending.directive.link_id != link.id); if self.ended.len() >= MAX_ENDED_REMEMBERED { self.ended.pop_front(); } @@ -936,9 +943,23 @@ impl FastLinks { !self.directives.is_empty() } - /// The next directive, its lifetime counted from `now`. + /// The next directive, its lifetime counted from `now`. A `host` or + /// `join` whose time has run out is skipped: the tick ends its link. pub(crate) fn next_directive(&mut self, now: Instant) -> Option { - let pending = self.directives.pop_front()?; + let pending = loop { + let pending = self.directives.pop_front()?; + let spent = pending.deadline.is_some_and(|deadline| now >= deadline); + if !spent || pending.directive.kind == FastLinkDirectiveKind::Close { + break pending; + } + }; + if let Some(link) = self.link.as_mut() { + if link.id == pending.directive.link_id + && pending.directive.kind != FastLinkDirectiveKind::Close + { + link.platform_engaged = true; + } + } let mut directive = pending.directive; directive.expires_in_ms = pending .deadline @@ -1583,6 +1604,48 @@ mod tests { assert!(android.peer().is_none()); } + #[test] + fn a_directive_the_platform_never_took_is_withdrawn_with_its_link() { + let t0 = Instant::now(); + // A paused platform drains nothing while the link times out. + let mut android = machine(host_roles()); + android.request(HIGH, fresh(1), t0).unwrap(); + android.tick(t0 + HOSTING_TIMEOUT, |_| false); + assert!( + android.next_directive(t0 + HOSTING_TIMEOUT).is_none(), + "no stale host, and no close owed" + ); + + // A join whose time ran out before it was taken is skipped. + let mut iphone = machine(join_roles()); + let id = fresh(2).link_id; + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer)), + fresh(3), + t0, + 0, + ); + assert!( + iphone.next_directive(t0 + OFFER_TTL).is_none(), + "no prompt for a spent offer" + ); + iphone.tick(t0 + OFFER_TTL, |_| false); + assert!( + iphone.next_directive(t0 + OFFER_TTL).is_none(), + "nothing was taken, so no close" + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index a1baebcc1..833fa0f9c 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -105,7 +105,9 @@ lifetime from the moment it arrived. ## Ending a link Every end, whatever its cause, does the same three things: a `close` directive -for this device's platform when the platform holds anything for the link, a +for this device's platform when the platform has taken a directive for the +link (one it has not taken yet is withdrawn instead, so a paused platform +never brings up, or prompts for, a network after its link ended), a `close` frame for the peer when the peer knows of the link and the end did not come from the peer, and one `fast_link_changed` event with state `closed` and the reason. From 4dbf9302cc212c7fa114ebef95b6f0fe16ec50a3 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:28:58 +0530 Subject: [PATCH 13/81] fix(bindings): an offer android cannot join is refused, not a crash WifiP2pConfig.Builder throws for a network name that does not start DIRECT- and two characters, and the engine accepts any name an iphone could join. an offer with such a name, from any session peer or another implementation of the spec, threw on the transport looper and killed an android joiner, again on every offer. the builder is now guarded and the offer answered invalid, and each directive runs inside a catch so a framework exception (a revoked permission, say) ends the link as failed instead. --- .../com/offlineprotocol/WifiDirectManager.kt | 59 +++++++++++++++---- .../FastLinkGroupConfigTest.kt | 41 +++++++++++++ 2 files changed, 88 insertions(+), 12 deletions(-) create mode 100644 bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkGroupConfigTest.kt diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index c84920b30..bdaf04f2d 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1481,10 +1481,22 @@ class WifiDirectManager( } catch (e: Exception) { null } ?: return - when (directive.kind) { - "host" -> hostFastLink(directive) - "join" -> joinFastLink(directive) - "close" -> closeFastLink(directive.linkId) + // One directive never takes the process down: everything below + // runs on the transport looper, where an exception is a crash. + try { + when (directive.kind) { + "host" -> hostFastLink(directive) + "join" -> joinFastLink(directive) + "close" -> closeFastLink(directive.linkId) + } + } catch (e: Exception) { + emitDiagnostic("warning", "Fast link: a directive failed", mapOf( + "kind" to directive.kind, + "error" to (e.javaClass.simpleName), + )) + if (fastLinkHosted?.linkId == directive.linkId) fastLinkHosted = null + if (fastLinkJoined?.linkId == directive.linkId) fastLinkJoined = null + if (directive.kind != "close") fastLinkEnded(directive.linkId, "failed") } } } @@ -1497,14 +1509,9 @@ class WifiDirectManager( } } - private fun fastLinkConfig(ssid: String, passphrase: String): WifiP2pConfig? { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null - return WifiP2pConfig.Builder() - .setNetworkName(ssid) - .setPassphrase(passphrase) - .enablePersistentMode(false) - .build() - } + private fun fastLinkConfig(ssid: String, passphrase: String): WifiP2pConfig? = + FastLinkGroupConfig.build(ssid, passphrase) + /** * Brings up a group with the engine's credentials. Reported to the engine @@ -1554,6 +1561,11 @@ class WifiDirectManager( val p2p = wifiP2pManager val ch = channel val config = if (ssid != null && passphrase != null) fastLinkConfig(ssid, passphrase) else null + if (config == null && ssid != null && passphrase != null && fastLinkSupported) { + // An offer whose network Android cannot join by name. + fastLinkEnded(directive.linkId, "invalid") + return + } if (config == null || host == null || port == null || p2p == null || ch == null || inGroup || fastLinkHosted != null || fastLinkJoined != null ) { @@ -2153,3 +2165,26 @@ internal object WifiDirectFormationProgress { return State(startedAt, passed) to Report(elapsed, passed) } } + +/** + * The Wi-Fi Direct group a fast link names (ADR 0038), or null where Android + * cannot make one: below Android 10, or for a name or passphrase it refuses. + * `WifiP2pConfig.Builder` throws for a name that does not start `DIRECT-` and + * two characters, which the engine allows (an iPhone joins any name), so an + * offer from another implementation must never reach the builder unguarded: + * on the transport looper the throw is a crash. + */ +internal object FastLinkGroupConfig { + fun build(ssid: String, passphrase: String): WifiP2pConfig? { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return null + return try { + WifiP2pConfig.Builder() + .setNetworkName(ssid) + .setPassphrase(passphrase) + .enablePersistentMode(false) + .build() + } catch (e: IllegalArgumentException) { + null + } + } +} diff --git a/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkGroupConfigTest.kt b/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkGroupConfigTest.kt new file mode 100644 index 000000000..293557775 --- /dev/null +++ b/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkGroupConfigTest.kt @@ -0,0 +1,41 @@ +package com.offlineprotocol + +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * [FastLinkGroupConfig]: a fast-link offer names any network the engine + * accepts, and an Android joiner must turn one it cannot make into a refusal, + * not a crash (ADR 0038). + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class FastLinkGroupConfigTest { + private val passphrase = "0123456789abcdef0123456789abcdef" + + @Test + fun `the engine's own name builds a group`() { + assertNotNull(FastLinkGroupConfig.build("DIRECT-5d-6582af4ee017", passphrase)) + } + + @Test + fun `a name android refuses is null, never a throw`() { + assertNull(FastLinkGroupConfig.build("HomeNetwork", passphrase)) + assertNull(FastLinkGroupConfig.build("DIRECT-", passphrase)) + } + + @Test + fun `a passphrase android refuses is null, never a throw`() { + assertNull(FastLinkGroupConfig.build("DIRECT-5d-6582af4ee017", "short")) + } + + @Test + @Config(sdk = [28]) + fun `below android 10 there is no group by name`() { + assertNull(FastLinkGroupConfig.build("DIRECT-5d-6582af4ee017", passphrase)) + } +} From 0061bc44ce4a4ed3f6f8a3269a7fca7e99b17959 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:30:02 +0530 Subject: [PATCH 14/81] fix(bindings): take a fast-link group down while paused, and start none android skipped its fast-link directives while paused, close included, so a link that ended with the app in the background left its wi-fi direct group on the air, and blocking every later link, until the app came back. the directives are now drained whatever the pause; while paused a close still runs and a new host or join is refused as background, on ios too, where a join would have prompted a user who is not looking. --- .../com/offlineprotocol/WifiDirectManager.kt | 22 +++++++++++-------- .../react-native/ios/WifiDirectManager.swift | 6 +++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index bdaf04f2d..c4d00d91c 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1462,13 +1462,14 @@ class WifiDirectManager( /** * The engine's wake-up, for its fast-link directives: posted like the - * body drain, and paused with it. Separate from [onMessagesAvailable], - * whose drain stops at "no stream yet", because a directive is what - * brings the first stream up. A paused transport answers when the poll - * resumes, and the engine's timers cover the wait. + * body drain. Separate from [onMessagesAvailable], whose drain stops at + * "no stream yet", because a directive is what brings the first stream + * up. Not paused with it: a `close` must take a group down while the app + * is in the background, or the group stays on the air, and blocks every + * later link, until the app returns. What a pause refuses is a new + * network ([drainFastLinkDirectives]). */ fun onFastLinkWake() { - if (isPaused) return transportHandler.post { drainFastLinkDirectives() } } @@ -1484,10 +1485,13 @@ class WifiDirectManager( // One directive never takes the process down: everything below // runs on the transport looper, where an exception is a crash. try { - when (directive.kind) { - "host" -> hostFastLink(directive) - "join" -> joinFastLink(directive) - "close" -> closeFastLink(directive.linkId) + when { + directive.kind == "close" -> closeFastLink(directive.linkId) + // No new network from the background: the user is not + // looking, and the engine's timers would end it anyway. + isPaused -> fastLinkEnded(directive.linkId, "background") + directive.kind == "host" -> hostFastLink(directive) + directive.kind == "join" -> joinFastLink(directive) } } catch (e: Exception) { emitDiagnostic("warning", "Fast link: a directive failed", mapOf( diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 2aeef27a9..9aa1ff63e 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -892,6 +892,12 @@ extension WifiDirectManager { fileprivate func drainFastLinkDirectives() { guard state == .running else { return } while let directive = protocolInstance.wifiDirectNextFastLinkDirective() { + // From the background a join would prompt a user who is not + // looking, and iOS would drop the network 15 s later anyway. + if isPaused, directive.kind != "close" { + protocolInstance.wifiDirectFastLinkEnded(linkId: directive.linkId, reason: "background") + continue + } switch directive.kind { case "join": joinFastLink(directive) From 2f59bdf9a7709602bf737a9752f9b788d21b5091 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:31:52 +0530 Subject: [PATCH 15/81] fix(protocol): a peer whose network was declined cannot prompt again at once an offer needs no request, so any session peer could put the ios join prompt in front of a user who never asked, and again the moment it was declined. after the user declines a peer's network, that peer's offers are answered declined for ten minutes and never shown; the user's own request to it ends the pause. threat model r34 records what is left: one prompt per ten minutes per session. --- crates/offline-protocol/src/fast_link.rs | 90 ++++++++++++++++++++++++ docs/security/threat-model.md | 5 +- docs/state-machines/fast-link.md | 6 +- 3 files changed, 99 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index d2689b417..7257a0669 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -64,6 +64,12 @@ pub const PASSPHRASE_HEX_LEN: usize = 32; /// the clock slack. pub const ENDED_MEMORY: Duration = Duration::from_millis(MAX_OFFER_TTL_MS + 300_000); +/// How long, after this device's user declined a peer's network, that peer's +/// unrequested offers are refused. Every join on iOS puts a system prompt in +/// front of the user; without a pause a session peer could put up another +/// the moment one was declined. +pub const DECLINE_BACKOFF: Duration = Duration::from_secs(600); + /// How many ended link ids are remembered. One link at a time, so a few. pub const MAX_ENDED_REMEMBERED: usize = 16; @@ -492,6 +498,9 @@ pub(crate) struct FastLinks { /// reached the host after the requester had given up, and its offer then /// prompted the requester's user to join a network already removed. ended: VecDeque<(String, Instant)>, + /// Peers whose network this device's user declined, and when; their + /// offers are refused for [`DECLINE_BACKOFF`] unless the user asks. + declined: VecDeque<(String, Instant)>, } impl FastLinks { @@ -518,6 +527,8 @@ impl FastLinks { Err(FastLinkRefusal::Busy) }; } + // The user asking is the user's answer to an earlier decline. + self.declined.retain(|(declined, _)| declined != peer); if self.roles.can_host { let id = fresh.link_id.clone(); self.start_host(peer, fresh, now, false); @@ -713,6 +724,12 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::Invalid); return; } + self.declined + .retain(|(_, at)| now.saturating_duration_since(*at) < DECLINE_BACKOFF); + if self.declined.iter().any(|(declined, _)| declined == peer) { + self.reply_close(peer, link_id, CloseReason::Declined); + return; + } if let Some(link) = self.link.clone() { if link.peer != peer { self.reply_close(peer, link_id, CloseReason::Busy); @@ -898,6 +915,12 @@ impl FastLinks { if self.ended.len() >= MAX_ENDED_REMEMBERED { self.ended.pop_front(); } + if reason == CloseReason::Declined && link.role == FastLinkRole::Join { + if self.declined.len() >= MAX_ENDED_REMEMBERED { + self.declined.pop_front(); + } + self.declined.push_back((link.peer.clone(), now)); + } self.ended.push_back((link.id.clone(), now)); if link.platform_engaged { self.directives.push_back(PendingDirective { @@ -1646,6 +1669,73 @@ mod tests { ); } + #[test] + fn a_declined_peer_cannot_prompt_again_until_the_user_asks() { + let t0 = Instant::now(); + let offer = |id: &str, links: &mut FastLinks, at: Instant| { + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + links.on_frame( + LOW, + HIGH, + Frame::new(id, FrameBody::Offer(offer)), + fresh(9), + at, + 0, + ); + }; + let mut iphone = machine(join_roles()); + let first = fresh(1).link_id; + offer(&first, &mut iphone, t0); + iphone.next_directive(t0); + assert!(iphone.platform_ended(&first, CloseReason::Declined, t0)); + iphone.take_frames(); + + // Another unasked-for offer at once: refused, no prompt. + let second = fresh(2).link_id; + offer(&second, &mut iphone, t0 + Duration::from_secs(1)); + assert!(!iphone.has_directives()); + assert_eq!( + iphone.take_frames()[0].1.body, + FrameBody::Close { + reason: "declined".to_string() + } + ); + + // After the backoff it may prompt again. + let third = fresh(3).link_id; + offer(&third, &mut iphone, t0 + DECLINE_BACKOFF); + assert_eq!( + iphone.next_directive(t0 + DECLINE_BACKOFF).unwrap().kind, + FastLinkDirectiveKind::Join + ); + iphone.close(LOW, t0 + DECLINE_BACKOFF); + iphone.take_frames(); + + // And the user's own request clears it at once. + let fourth = fresh(4).link_id; + offer(&fourth, &mut iphone, t0 + DECLINE_BACKOFF); + iphone.next_directive(t0); + iphone.platform_ended(&fourth, CloseReason::Declined, t0 + DECLINE_BACKOFF); + let asked = iphone.request(LOW, fresh(5), t0 + DECLINE_BACKOFF).unwrap(); + iphone.take_frames(); + offer( + &asked, + &mut iphone, + t0 + DECLINE_BACKOFF + Duration::from_secs(1), + ); + assert_eq!( + iphone.next_directive(t0 + DECLINE_BACKOFF).unwrap().kind, + FastLinkDirectiveKind::Join + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 0665e5f80..63a828272 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1480,7 +1480,10 @@ and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial is bound to the Wi-Fi interface, and the stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most -300 s later. While a joiner is on the host's network the host is its access +300 s later. It can also put the iOS join prompt in front of a user who did +not ask: an offer needs no request. Once the user declines, that peer's +offers are refused for ten minutes, so the most it gets is one prompt per ten +minutes per session. While a joiner is on the host's network the host is its access point, and sees whatever else the joiner's device sends there, as any access point does: name lookups and connection attempts of other applications, with no route onward. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 833fa0f9c..c70539d42 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -77,7 +77,11 @@ the request means the first one was lost. Otherwise it starts hosting under the request's link id. **An `offer` arrives.** A device that cannot join answers `close` -(`cannot_join`), and one holding a link with another peer answers `busy`. An +(`cannot_join`), and one holding a link with another peer answers `busy`. For +ten minutes after this device's user declined a peer's network, that peer's +offers are answered `declined` and never shown: each join on iOS is a system +prompt, and without the pause a peer could put up another the moment one was +refused. The user's own request to that peer ends the pause. An offer that fails validation (below) is answered `close` (`invalid`) and nothing else happens. When both devices are hosting for each other, the lower address keeps hosting: the higher one closes its own link and joins, and the lower one From f7e8aacf029803d54f6a50ab84169f580896bfd1 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:33:27 +0530 Subject: [PATCH 16/81] fix(protocol): remember a close that overtakes its offer a host's close can reach the joiner before the late offer it ends, and a close for a link the joiner did not hold was dropped without trace, so the offer then prompted. its link id is now remembered like an ended link's, and the offer is refused as late when it lands. --- crates/offline-protocol/src/fast_link.rs | 53 ++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 7257a0669..19f112210 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -661,6 +661,10 @@ impl FastLinks { .is_some_and(|link| link.id == frame.link && link.peer == peer) { self.end(CloseReason::parse(&reason), false, now); + } else { + // A close can overtake the offer it ends: remembered, so + // the offer is refused as late when it lands. + self.remember_ended(&frame.link, now); } } } @@ -889,6 +893,13 @@ impl FastLinks { } } + fn remember_ended(&mut self, link_id: &str, now: Instant) { + if self.ended.len() >= MAX_ENDED_REMEMBERED { + self.ended.pop_front(); + } + self.ended.push_back((link_id.to_string(), now)); + } + fn ended_recently(&mut self, link_id: &str, now: Instant) -> bool { while self .ended @@ -912,16 +923,13 @@ impl FastLinks { // a join prompt in front of the user for one already gone. self.directives .retain(|pending| pending.directive.link_id != link.id); - if self.ended.len() >= MAX_ENDED_REMEMBERED { - self.ended.pop_front(); - } + self.remember_ended(&link.id, now); if reason == CloseReason::Declined && link.role == FastLinkRole::Join { if self.declined.len() >= MAX_ENDED_REMEMBERED { self.declined.pop_front(); } self.declined.push_back((link.peer.clone(), now)); } - self.ended.push_back((link.id.clone(), now)); if link.platform_engaged { self.directives.push_back(PendingDirective { directive: FastLinkDirective { @@ -1736,6 +1744,43 @@ mod tests { ); } + #[test] + fn a_close_that_overtakes_its_offer_keeps_the_offer_from_prompting() { + let t0 = Instant::now(); + let mut iphone = machine(join_roles()); + let id = fresh(1).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new( + &id, + FrameBody::Close { + reason: "expired".to_string(), + }, + ), + fresh(2), + t0, + 0, + ); + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer)), + fresh(3), + t0, + 0, + ); + assert!(!iphone.has_directives()); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); From 01e3f79e64b15ec3efd0fb9432961b4724486c6b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:33:56 +0530 Subject: [PATCH 17/81] fix(bindings): group formation waits while a fast link holds the radio formation checked only inGroup, which turns true when the group broadcast lands, seconds after a fast link's createGroup or connect: in that window it could issue its own join or create and break the one-group rule of adr 0038. it now waits while a fast link is hosted or joined. --- .../src/main/java/com/offlineprotocol/WifiDirectManager.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index c4d00d91c..6a6894e1e 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1127,6 +1127,9 @@ class WifiDirectManager( // Nothing to form over while Wi-Fi P2P is off: every call would fail // BUSY, and a join attempted then is refused with no group to find. if (!p2pUp) return + // A fast link holds the one group this device can own or join, from + // its createGroup or connect on, which is before `inGroup` says so. + if (fastLinkHosted != null || fastLinkJoined != null) return val now = SystemClock.elapsedRealtime() adverts.values.removeAll { now - it.seenAtMs > ADVERT_TTL_MS } deadOwners.values.removeAll { now - it >= WifiDirectGroupFormation.DEAD_OWNER_TTL_MS } From 399df3b58bf2e5abd3826b1a03c4b9fd8b6d536f Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:43:37 +0530 Subject: [PATCH 18/81] fix(protocol): blocking a peer ends its fast link blocking removed the peer's capability but left its link standing: the android group stayed up for the blocked peer, an iphone joiner stayed off its own wi-fi, and the blocked peer's own bodies kept the link from going idle. block_user now ends the link, telling this device's platform to take the network down and sending nothing to the blocked peer. --- crates/offline-protocol/src/fast_link.rs | 10 +++++++ .../offline-protocol/src/protocol/blocking.rs | 4 +++ .../src/protocol/fast_link.rs | 8 ++++++ .../src/protocol/tests/fast_link.rs | 28 +++++++++++++++++++ 4 files changed, 50 insertions(+) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 19f112210..3b1ade8ce 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -826,6 +826,16 @@ impl FastLinks { true } + /// Ends the link with `peer` without telling the peer: this device's user + /// blocked it, and nothing more is sent to a blocked peer. + pub(crate) fn forget(&mut self, peer: &str, now: Instant) -> bool { + if self.peer() != Some(peer) { + return false; + } + self.end(CloseReason::Closed, false, now); + true + } + /// A stream proved `peer`. pub(crate) fn stream_proved(&mut self, peer: &str, now: Instant) { let Some(link) = self.link.as_mut() else { diff --git a/crates/offline-protocol/src/protocol/blocking.rs b/crates/offline-protocol/src/protocol/blocking.rs index 77fc1c9c3..7a7ad105c 100644 --- a/crates/offline-protocol/src/protocol/blocking.rs +++ b/crates/offline-protocol/src/protocol/blocking.rs @@ -64,6 +64,10 @@ impl OfflineProtocol { // the end of a lease the blocked peer can no longer renew. self.end_subscriptions_with(user_id); + // So does a fast link with the user: its network stays up for the + // peer otherwise, and an iPhone joiner stays off its own Wi-Fi. + self.end_fast_link_with_blocked(user_id); + info!(user_id = %user_id, "User blocked"); if let Ok(state) = lock_shared_state(&self.shared_state) { diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index abd7393ef..fea9119f8 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -83,6 +83,14 @@ impl OfflineProtocol { closed } + /// The user blocked `peer`: its link ends here and on this platform, + /// with nothing sent to it. + pub(crate) fn end_fast_link_with_blocked(&mut self, peer: &str) { + if self.fast_links.forget(peer, Instant::now()) { + self.flush_fast_link(); + } + } + /// The next instruction for the platform. Drained whenever the peer-stream /// callback fires. pub fn next_fast_link_directive(&mut self) -> Option { diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index ad7c9e573..595282513 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -350,3 +350,31 @@ fn fast_link_frames_prefer_bluetooth_over_the_peer_stream() { bob.deliver(over_bluetooth); assert!(bob.protocol.next_fast_link_directive().is_some()); } + +/// Blocking a peer ends its fast link at once: the platform takes the network +/// down, and nothing is sent to the blocked peer. +#[test] +fn blocking_a_peer_ends_its_fast_link() { + let (mut alice, bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + alice.protocol.fast_link_stream_proved(&bob.address); + alice.take_sent(); + + alice.protocol.block_user(&bob.address).unwrap(); + let close = alice.protocol.next_fast_link_directive().unwrap(); + assert_eq!(close.kind, FastLinkDirectiveKind::Close); + assert_eq!(close.link_id, link_id); + assert!( + alice.take_sent().is_empty(), + "nothing goes to a blocked peer" + ); + assert_eq!( + alice.link_states().last().unwrap(), + &("closed".to_string(), Some("closed".to_string())) + ); +} From 17453e1e164e99125ba0c36de1039d74edbd2cc3 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:45:02 +0530 Subject: [PATCH 19/81] fix(protocol): a second offer while joining is refused, not swapped in a new offer from the same peer replaced a link being joined. on ios the replaced join's completion then never reported the user's decline, so a peer that re-offered while each prompt was on screen never started the ten-minute decline pause that r34 relies on. the second offer is now answered busy and the first stands; an honest host's new network follows its own close. r34 also records that an android joiner joins with no prompt at all. --- crates/offline-protocol/src/fast_link.rs | 69 ++++++++++++++++++++++-- docs/security/threat-model.md | 8 ++- docs/state-machines/fast-link.md | 6 ++- 3 files changed, 77 insertions(+), 6 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 3b1ade8ce..4f5e9b74a 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -754,9 +754,14 @@ impl FastLinks { return; } if link.state != FastLinkState::Requested { - // A new offer replaces the one before it: the host - // brought up a new network. Nothing to tell it. - self.end(CloseReason::Failed, false, now); + // A second offer while one is being joined or is up + // is refused, never swapped in. An honest host's new + // network follows its own close, which ends this + // link first. Swapping let a peer re-offer while each + // prompt was on screen, so the user's decline was + // never reported and the decline pause never began. + self.reply_close(peer, link_id, CloseReason::Busy); + return; } else { // The offer answers our request; it supersedes the // request's link quietly, whatever id the host chose. @@ -1791,6 +1796,64 @@ mod tests { assert!(!iphone.has_directives()); } + #[test] + fn a_second_offer_while_joining_is_refused_not_swapped_in() { + let t0 = Instant::now(); + let offer = || Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + let mut iphone = machine(join_roles()); + let first = fresh(1).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&first, FrameBody::Offer(offer())), + fresh(2), + t0, + 0, + ); + iphone.next_directive(t0); + iphone.take_changes(); + + let second = fresh(3).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&second, FrameBody::Offer(offer())), + fresh(4), + t0, + 0, + ); + assert!(!iphone.has_directives(), "no second prompt"); + assert!(iphone.take_changes().is_empty(), "the first link stands"); + let answer = iphone.take_frames(); + assert_eq!(answer[0].1.link, second); + assert_eq!( + answer[0].1.body, + FrameBody::Close { + reason: "busy".to_string() + } + ); + + // So the user's decline of the first reaches the engine, and holds. + assert!(iphone.platform_ended(&first, CloseReason::Declined, t0)); + let third = fresh(5).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&third, FrameBody::Offer(offer())), + fresh(6), + t0, + 0, + ); + assert!(!iphone.has_directives()); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 63a828272..6c9dfe43a 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1482,8 +1482,12 @@ is bound to the Wi-Fi interface, and the stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most 300 s later. It can also put the iOS join prompt in front of a user who did not ask: an offer needs no request. Once the user declines, that peer's -offers are refused for ten minutes, so the most it gets is one prompt per ten -minutes per session. While a joiner is on the host's network the host is its access +offers are refused for ten minutes, and a second offer while one is on screen +is refused, so the most it gets is one prompt per ten minutes per session. An +Android joiner shows no prompt at all: Wi-Fi Direct joins a group by name and +passphrase silently, so a session peer can move an Android device onto its +group whenever it is in range, bounded by the same lifetime and by the +stream's proof. While a joiner is on the host's network the host is its access point, and sees whatever else the joiner's device sends there, as any access point does: name lookups and connection attempts of other applications, with no route onward. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index c70539d42..927d5df07 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -81,7 +81,11 @@ the request's link id. ten minutes after this device's user declined a peer's network, that peer's offers are answered `declined` and never shown: each join on iOS is a system prompt, and without the pause a peer could put up another the moment one was -refused. The user's own request to that peer ends the pause. An +refused. The user's own request to that peer ends the pause. A second offer +from the peer while one is being joined or is up is answered `busy` and the +first stands: an honest host's new network follows its own `close`, and a +swap would let a peer re-offer while each prompt is on screen, so that no +decline is ever reported and the pause never begins. An offer that fails validation (below) is answered `close` (`invalid`) and nothing else happens. When both devices are hosting for each other, the lower address keeps hosting: the higher one closes its own link and joins, and the lower one From a1c1d10368dc4c0afb4de9570da7fc1fbc03ccb9 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:46:17 +0530 Subject: [PATCH 20/81] fix(bindings): an android that loses the host tie-break joins once its group is gone when two android devices host for each other the higher address closes its own link and joins the other's, and the engine hands its platform the close and the join in one drain. removeGroup is asynchronous, so the join found the device still in its group and failed, and both links ended. the join now waits for the group-gone broadcast, within the offer's lifetime, then runs. not exercised on hardware: it needs two android phones. --- .../com/offlineprotocol/WifiDirectManager.kt | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 6a6894e1e..705a4c3cc 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1445,6 +1445,12 @@ class WifiDirectManager( // admission check, the dial). @Volatile private var fastLinkHosted: FastLinkHosted? = null @Volatile private var fastLinkJoined: FastLinkJoined? = null + // A fast link's group is being removed (transport thread). Removal is + // asynchronous, so a join that follows a close in one drain finds the + // device still in that group. + private var fastLinkLeaving = false + // A join waiting for [fastLinkLeaving] to clear (transport thread). + private var parkedFastLinkJoin: FastLinkDirective? = null /** A group by name and passphrase, for creating or joining: Android 10. */ private val fastLinkSupported: Boolean @@ -1573,6 +1579,20 @@ class WifiDirectManager( fastLinkEnded(directive.linkId, "invalid") return } + if (config != null && inGroup && fastLinkLeaving && parkedFastLinkJoin == null) { + // Both devices hosted for each other, and this one, the higher + // address, closed its group to join the other's (ADR 0038). The + // close and the join arrive in one drain, before the removal + // lands: the join waits for the group to go, within its lifetime. + parkedFastLinkJoin = directive + transportHandler.postDelayed({ + if (parkedFastLinkJoin === directive) { + parkedFastLinkJoin = null + fastLinkEnded(directive.linkId, "failed") + } + }, directive.expiresInMs.toLong()) + return + } if (config == null || host == null || port == null || p2p == null || ch == null || inGroup || fastLinkHosted != null || fastLinkJoined != null ) { @@ -1602,12 +1622,15 @@ class WifiDirectManager( val ch = channel ?: return val hosted = fastLinkHosted val joined = fastLinkJoined + if (parkedFastLinkJoin?.linkId == linkId) parkedFastLinkJoin = null if (hosted?.linkId == linkId) { fastLinkHosted = null + fastLinkLeaving = inGroup p2p.removeGroup(ch, quietListener("remove fast-link group")) } if (joined?.linkId == linkId) { fastLinkJoined = null + fastLinkLeaving = inGroup if (!joined.connected) p2p.cancelConnect(ch, quietListener("cancel fast-link join")) p2p.removeGroup(ch, quietListener("leave fast-link group")) } @@ -1651,6 +1674,15 @@ class WifiDirectManager( /** This device left whatever group it was in. */ private fun fastLinkGroupGone() { + fastLinkLeaving = false + parkedFastLinkJoin?.let { parked -> + parkedFastLinkJoin = null + try { + joinFastLink(parked) + } catch (e: Exception) { + fastLinkEnded(parked.linkId, "failed") + } + } val hosted = fastLinkHosted if (hosted != null && hosted.reported) { fastLinkHosted = null @@ -1668,8 +1700,12 @@ class WifiDirectManager( private fun endFastLinkOnStop() { val hosted = fastLinkHosted val joined = fastLinkJoined + val parked = parkedFastLinkJoin fastLinkHosted = null fastLinkJoined = null + parkedFastLinkJoin = null + fastLinkLeaving = false + parked?.let { fastLinkEnded(it.linkId, "failed") } val ch = channel if ((hosted != null || joined != null) && ch != null) { wifiP2pManager?.removeGroup(ch, quietListener("end fast link on stop")) From 317637d7747d512f2cebce8bd701c02fd5d8b710 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:58:24 +0530 Subject: [PATCH 21/81] fix(protocol): a decline counts after the peer closed its link a peer could close its link while the ios prompt was on screen: the user's cancel then landed on a link the engine no longer held and was dropped, so the decline pause never began and the next offer prompted again. the engine remembers which peer each ended join belonged to and records a decline reported after the end against it, and ios reports the refusal even when the link is already gone. --- .../react-native/ios/WifiDirectManager.swift | 5 ++ crates/offline-protocol/src/fast_link.rs | 89 +++++++++++++++++-- 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 9aa1ff63e..35190b050 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -940,6 +940,11 @@ extension WifiDirectManager { guard fastLink === link else { // Closed while the user read the prompt: leave what was joined. NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: link.ssid) + // A refusal still counts against the peer, which may have closed + // its link on purpose to keep the user's Cancel from registering. + if error?.code == Self.HOTSPOT_USER_DENIED { + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "declined") + } return } if let error = error, error.code != Self.HOTSPOT_ALREADY_ASSOCIATED { diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 4f5e9b74a..6d939bc83 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -501,6 +501,11 @@ pub(crate) struct FastLinks { /// Peers whose network this device's user declined, and when; their /// offers are refused for [`DECLINE_BACKOFF`] unless the user asks. declined: VecDeque<(String, Instant)>, + /// Joined links that ended, and their peer, so a decline the platform + /// reports after the link ended still counts against that peer: a peer + /// could otherwise close its link while the prompt was on screen, and the + /// user's Cancel would be reported for a link the engine no longer held. + ended_joins: VecDeque<(String, String)>, } impl FastLinks { @@ -818,7 +823,17 @@ impl FastLinks { self.end(reason, true, now); true } - _ => false, + _ => { + // The link already ended, from the peer's close while the + // prompt was up, say. The user's refusal still stands. + if reason == CloseReason::Declined { + if let Some((_, peer)) = self.ended_joins.iter().find(|(id, _)| id == link_id) { + let peer = peer.clone(); + self.record_decline(peer, now); + } + } + false + } } } @@ -908,6 +923,13 @@ impl FastLinks { } } + fn record_decline(&mut self, peer: String, now: Instant) { + if self.declined.len() >= MAX_ENDED_REMEMBERED { + self.declined.pop_front(); + } + self.declined.push_back((peer, now)); + } + fn remember_ended(&mut self, link_id: &str, now: Instant) { if self.ended.len() >= MAX_ENDED_REMEMBERED { self.ended.pop_front(); @@ -939,11 +961,15 @@ impl FastLinks { self.directives .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); - if reason == CloseReason::Declined && link.role == FastLinkRole::Join { - if self.declined.len() >= MAX_ENDED_REMEMBERED { - self.declined.pop_front(); + if link.role == FastLinkRole::Join { + if self.ended_joins.len() >= MAX_ENDED_REMEMBERED { + self.ended_joins.pop_front(); + } + self.ended_joins + .push_back((link.id.clone(), link.peer.clone())); + if reason == CloseReason::Declined { + self.record_decline(link.peer.clone(), now); } - self.declined.push_back((link.peer.clone(), now)); } if link.platform_engaged { self.directives.push_back(PendingDirective { @@ -1854,6 +1880,59 @@ mod tests { assert!(!iphone.has_directives()); } + #[test] + fn a_decline_counts_after_the_peer_closed_its_link() { + let t0 = Instant::now(); + let offer = || Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + let mut iphone = machine(join_roles()); + let first = fresh(1).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&first, FrameBody::Offer(offer())), + fresh(2), + t0, + 0, + ); + iphone.next_directive(t0); + // The peer closes its link while the prompt is on screen... + iphone.on_frame( + LOW, + HIGH, + Frame::new( + &first, + FrameBody::Close { + reason: "closed".to_string(), + }, + ), + fresh(3), + t0, + 0, + ); + iphone.next_directive(t0); + // ...and the user's Cancel arrives for a link the engine let go. + assert!(!iphone.platform_ended(&first, CloseReason::Declined, t0)); + iphone.take_frames(); + + let second = fresh(4).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&second, FrameBody::Offer(offer())), + fresh(5), + t0, + 0, + ); + assert!(!iphone.has_directives(), "the decline holds: no new prompt"); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); From efb6a0b4c6a359e3263a4d571bd4f728b17520a6 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:59:04 +0530 Subject: [PATCH 22/81] fix(bindings): an android joiner dials the group owner, not the offer's host the dial went to the address the offer named, checked only to be private or link-local. an android joiner stays on its own wi-fi while in a p2p group, so an offer naming a host on the user's home network sent the dial, and a preamble, there instead of over the group. the dial now always goes to the owner's own address as the group reports it, on the offer's port. --- .../com/offlineprotocol/WifiDirectManager.kt | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 705a4c3cc..6334a0ebd 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1435,7 +1435,8 @@ class WifiDirectManager( private class FastLinkJoined( val linkId: String, val peer: String, - val host: String, + // The offer's port. Its host is not kept: the dial goes to the + // owner's address the group reports ([connectToGroupOwner]). val port: Int, ) { @Volatile var connected = false @@ -1599,7 +1600,7 @@ class WifiDirectManager( fastLinkEnded(directive.linkId, "failed") return } - val joined = FastLinkJoined(directive.linkId, directive.peerId, host, port) + val joined = FastLinkJoined(directive.linkId, directive.peerId, port) fastLinkJoined = joined emitDiagnostic("info", "Fast link: joining a network", mapOf("linkId" to directive.linkId)) p2p.connect(ch, config, object : WifiP2pManager.ActionListener { @@ -1797,15 +1798,18 @@ class WifiDirectManager( socketExecutor.execute { var ran = PeerStreamSockets.Ran(proved = null, heard = false) try { - // A fast link names the owner's address, port and identity in - // its offer; any other group's owner is dialled on the group - // port and proves whoever it is. + // A fast link's offer names the owner's port and identity; + // any other group's owner is dialled on the group port and + // proves whoever it is. The address is always the owner's + // own, from the group: never the offer's, which could name a + // host on the Wi-Fi network this device also stays on, and + // send the dial off the group (ADR 0038, decision 6). val joined = fastLinkJoined val socket = Socket() try { socket.connect( InetSocketAddress( - joined?.host ?: address, + address, joined?.port ?: PeerStreamListener.GROUP_OWNER_PORT, ), CONNECTION_TIMEOUT_MS.toInt(), From b64ecb98f519c1e1f35470fdbae2d944e33c6ed0 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:59:46 +0530 Subject: [PATCH 23/81] fix(bindings): remove a fast-link group that comes up after its link closed a close that landed while createGroup was still negotiating sent a removeGroup the framework can refuse as busy, and the group then came up with nothing tracking it, blocking every later link and group formation until the transport stopped. the name of a group closed before it came up is now remembered, and the group is removed when it appears. --- .../com/offlineprotocol/WifiDirectManager.kt | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 6334a0ebd..eb62a9991 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1452,6 +1452,10 @@ class WifiDirectManager( private var fastLinkLeaving = false // A join waiting for [fastLinkLeaving] to clear (transport thread). private var parkedFastLinkJoin: FastLinkDirective? = null + // The name of a fast-link group closed before it came up (transport + // thread). Its removeGroup can lose to the negotiation, answered BUSY, and + // the group then appears with nothing tracking it; seen, it is removed. + private var orphanedFastLinkSsid: String? = null /** A group by name and passphrase, for creating or joining: Android 10. */ private val fastLinkSupported: Boolean @@ -1627,6 +1631,7 @@ class WifiDirectManager( if (hosted?.linkId == linkId) { fastLinkHosted = null fastLinkLeaving = inGroup + if (!hosted.reported) orphanedFastLinkSsid = hosted.ssid p2p.removeGroup(ch, quietListener("remove fast-link group")) } if (joined?.linkId == linkId) { @@ -1646,7 +1651,11 @@ class WifiDirectManager( */ @SuppressLint("MissingPermission") private fun fastLinkGroupChanged() { - val hosted = fastLinkHosted ?: return + val hosted = fastLinkHosted + if (hosted == null) { + removeOrphanedFastLinkGroup() + return + } wifiP2pManager?.requestGroupInfo(channel) { group -> if (fastLinkHosted !== hosted || group == null || !group.isGroupOwner || group.networkName != hosted.ssid @@ -1673,6 +1682,18 @@ class WifiDirectManager( } } + /** Removes the group a closed link brought up after it was closed. */ + @SuppressLint("MissingPermission") + private fun removeOrphanedFastLinkGroup() { + val orphan = orphanedFastLinkSsid ?: return + wifiP2pManager?.requestGroupInfo(channel) { group -> + if (group == null || !group.isGroupOwner || group.networkName != orphan) return@requestGroupInfo + orphanedFastLinkSsid = null + emitDiagnostic("info", "Fast link: removing a group that came up after its link closed") + wifiP2pManager?.removeGroup(channel, quietListener("remove orphaned fast-link group")) + } + } + /** This device left whatever group it was in. */ private fun fastLinkGroupGone() { fastLinkLeaving = false @@ -1706,6 +1727,7 @@ class WifiDirectManager( fastLinkJoined = null parkedFastLinkJoin = null fastLinkLeaving = false + orphanedFastLinkSsid = null parked?.let { fastLinkEnded(it.linkId, "failed") } val ch = channel if ((hosted != null || joined != null) && ch != null) { From 734bb1db967df245937bd00e8ec2f66d476c6be2 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 07:59:47 +0530 Subject: [PATCH 24/81] docs: point custody at the renamed state-machine invariant heading --- docs/spec/custody.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec/custody.md b/docs/spec/custody.md index f3c6916ab..6cbf54cd4 100644 --- a/docs/spec/custody.md +++ b/docs/spec/custody.md @@ -32,7 +32,7 @@ a protocol break rather than a refactor. retry ladder and park state are untouched by a deposit and untouched by a receipt. The failure this prevents is the one the sender-holds-custody invariant exists for - ([state machines](../state-machines/README.md#the-one-invariant-that-spans-all-seven)): + ([state machines](../state-machines/README.md#the-one-invariant-that-spans-all-eight)): a sender that released a message to a carrier which then walked away would have lost it silently. Under this chapter that case costs latency and nothing else. From 2abc9e1e8b76e7202239453943e0c6d493d1babe Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:09:31 +0530 Subject: [PATCH 25/81] fix(protocol): a host stops answering a peer whose links go unused any session peer could make an android host bring up a group by asking, and by asking again each time the offer expired keep a group on the air and the device's own formation locked out indefinitely. after two links in a row hosted for a peer's requests expire with no stream from it, the host answers that peer's requests busy for ten minutes; a used link resets the count, and the host's own request to the peer ends the pause. r34 records what is left. also, an offer that answers this device's request under another id now leaves the request's id remembered as ended, so a host acting on the request late cannot prompt the user for a second network. --- crates/offline-protocol/src/fast_link.rs | 181 ++++++++++++++++++++++- docs/security/threat-model.md | 6 +- docs/state-machines/fast-link.md | 11 +- 3 files changed, 195 insertions(+), 3 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 6d939bc83..97195b688 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -70,6 +70,18 @@ pub const ENDED_MEMORY: Duration = Duration::from_millis(MAX_OFFER_TTL_MS + 300_ /// the moment one was declined. pub const DECLINE_BACKOFF: Duration = Duration::from_secs(600); +/// Links in a row a host may bring up for a peer's requests that expire with +/// no stream from that peer before it stops answering them for +/// [`HOST_BACKOFF`]. Two, so an honest user who missed the prompt once can +/// ask again at once. +pub const MAX_UNANSWERED_HOSTINGS: u8 = 2; + +/// How long a host refuses a peer's requests after [`MAX_UNANSWERED_HOSTINGS`] +/// went unused. Without it a peer that never joins could keep a group on the +/// air, and the device's own group formation locked out, by requesting again +/// each time an offer expired. +pub const HOST_BACKOFF: Duration = Duration::from_secs(600); + /// How many ended link ids are remembered. One link at a time, so a few. pub const MAX_ENDED_REMEMBERED: usize = 16; @@ -482,6 +494,8 @@ struct Link { platform_engaged: bool, /// The peer knows of this link, so its end needs a `close` frame. peer_engaged: bool, + /// A host link brought up because the peer asked. + requested_by_peer: bool, } /// The machine. One link at a time (invariant 3). @@ -506,6 +520,11 @@ pub(crate) struct FastLinks { /// could otherwise close its link while the prompt was on screen, and the /// user's Cancel would be reported for a link the engine no longer held. ended_joins: VecDeque<(String, String)>, + /// Per peer, the links hosted in a row for its requests that expired + /// with no stream from it. + unanswered: VecDeque<(String, u8)>, + /// Peers whose requests are refused, and since when ([`HOST_BACKOFF`]). + host_backoff: VecDeque<(String, Instant)>, } impl FastLinks { @@ -532,8 +551,12 @@ impl FastLinks { Err(FastLinkRefusal::Busy) }; } - // The user asking is the user's answer to an earlier decline. + // The user asking is the user's answer to an earlier decline, and to + // the peer's unanswered requests. self.declined.retain(|(declined, _)| declined != peer); + self.unanswered.retain(|(unanswered, _)| unanswered != peer); + self.host_backoff + .retain(|(backed_off, _)| backed_off != peer); if self.roles.can_host { let id = fresh.link_id.clone(); self.start_host(peer, fresh, now, false); @@ -556,6 +579,7 @@ impl FastLinks { offer: None, platform_engaged: false, peer_engaged: true, + requested_by_peer: false, }); self.changed(None); Ok(id) @@ -587,6 +611,7 @@ impl FastLinks { offer: None, platform_engaged: false, peer_engaged, + requested_by_peer: peer_engaged, }); self.changed(None); } @@ -712,6 +737,16 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::CannotHost); return; } + self.host_backoff + .retain(|(_, at)| now.saturating_duration_since(*at) < HOST_BACKOFF); + if self + .host_backoff + .iter() + .any(|(backed_off, _)| backed_off == peer) + { + self.reply_close(peer, link_id, CloseReason::Busy); + return; + } // Under the requester's id, so its close and our offer name one link. let fresh = FreshLink { link_id: link_id.to_string(), @@ -770,6 +805,11 @@ impl FastLinks { } else { // The offer answers our request; it supersedes the // request's link quietly, whatever id the host chose. + // The request's id is remembered as ended, so a host + // that acts on the request late cannot prompt. + if link.id != link_id { + self.remember_ended(&link.id, now); + } self.link = None; } } @@ -805,6 +845,7 @@ impl FastLinks { offer: None, platform_engaged: false, peer_engaged: true, + requested_by_peer: false, }); self.changed(None); } @@ -923,6 +964,39 @@ impl FastLinks { } } + /// Counts a link hosted for `peer`'s request that ended: one its stream + /// used resets the count, one that expired unused adds to it, and + /// [`MAX_UNANSWERED_HOSTINGS`] in a row start [`HOST_BACKOFF`]. + fn count_hosting(&mut self, peer: &str, used: bool, reason: CloseReason, now: Instant) { + if used { + self.unanswered.retain(|(unanswered, _)| unanswered != peer); + return; + } + if reason != CloseReason::Expired { + return; + } + let count = match self.unanswered.iter_mut().find(|(p, _)| p == peer) { + Some((_, count)) => { + *count = count.saturating_add(1); + *count + } + None => { + if self.unanswered.len() >= MAX_ENDED_REMEMBERED { + self.unanswered.pop_front(); + } + self.unanswered.push_back((peer.to_string(), 1)); + 1 + } + }; + if count >= MAX_UNANSWERED_HOSTINGS { + self.unanswered.retain(|(unanswered, _)| unanswered != peer); + if self.host_backoff.len() >= MAX_ENDED_REMEMBERED { + self.host_backoff.pop_front(); + } + self.host_backoff.push_back((peer.to_string(), now)); + } + } + fn record_decline(&mut self, peer: String, now: Instant) { if self.declined.len() >= MAX_ENDED_REMEMBERED { self.declined.pop_front(); @@ -961,6 +1035,9 @@ impl FastLinks { self.directives .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); + if link.role == FastLinkRole::Host && link.requested_by_peer { + self.count_hosting(&link.peer, link.state == FastLinkState::Up, reason, now); + } if link.role == FastLinkRole::Join { if self.ended_joins.len() >= MAX_ENDED_REMEMBERED { self.ended_joins.pop_front(); @@ -1933,6 +2010,108 @@ mod tests { assert!(!iphone.has_directives(), "the decline holds: no new prompt"); } + #[test] + fn requests_that_go_unused_twice_are_refused_for_a_while() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let host_once = |android: &mut FastLinks, seed: u8, at: Instant| { + let id = fresh(seed).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(seed + 1), + at, + 0, + ); + let hosted = android.next_directive(at).map(|d| d.kind); + if hosted.is_some() { + android.hosting(&id, "192.168.49.1", 8988, at, 0); + android.tick(at + OFFER_TTL, |_| false); + android.next_directive(at + OFFER_TTL); + } + android.take_frames(); + hosted + }; + assert_eq!( + host_once(&mut android, 1, t0), + Some(FastLinkDirectiveKind::Host) + ); + assert_eq!( + host_once(&mut android, 3, t0), + Some(FastLinkDirectiveKind::Host), + "one miss is forgiven" + ); + assert_eq!( + host_once(&mut android, 5, t0), + None, + "two in a row: refused" + ); + assert_eq!( + host_once(&mut android, 7, t0 + OFFER_TTL + HOST_BACKOFF), + Some(FastLinkDirectiveKind::Host), + "until the backoff ends" + ); + + // The host's own request to that peer ends the backoff at once. + let mut android = machine(host_roles()); + host_once(&mut android, 1, t0); + host_once(&mut android, 3, t0); + let own = android.request(HIGH, fresh(9), t0).unwrap(); + android.close(HIGH, t0); + let _ = own; + android.next_directive(t0); + android.take_frames(); + assert_eq!( + host_once(&mut android, 11, t0), + Some(FastLinkDirectiveKind::Host) + ); + } + + #[test] + fn a_superseded_request_cannot_be_hosted_into_a_prompt_later() { + let t0 = Instant::now(); + let mut iphone = machine(join_roles()); + let request_id = iphone.request(LOW, fresh(1), t0).unwrap(); + iphone.take_frames(); + // The peer's own link arrives instead and supersedes the request. + let offer = || Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + let theirs = fresh(2).link_id; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&theirs, FrameBody::Offer(offer())), + fresh(3), + t0, + 0, + ); + iphone.next_directive(t0); + iphone.close(LOW, t0); + iphone.next_directive(t0); + iphone.take_frames(); + + // The request reaches the host late, and its offer arrives. + iphone.on_frame( + LOW, + HIGH, + Frame::new(&request_id, FrameBody::Offer(offer())), + fresh(4), + t0, + 0, + ); + assert!( + !iphone.has_directives(), + "no prompt for a request already answered" + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 6c9dfe43a..d127a228c 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1494,7 +1494,11 @@ no route onward. **Availability:** anyone who can drop Bluetooth frames between the two can stop a link from forming, which is no more than they could already do to the -messages themselves. The traffic stays on Bluetooth. +messages themselves. The traffic stays on Bluetooth. A session peer can make +an Android host bring up a group by asking, and holds the device's one group +(and so its own group formation) while it lasts: at most two offer lifetimes, +about four minutes, before the host stops answering that peer's requests for +ten minutes. **Why it stands:** a network that does not broadcast its existence cannot be joined by an iPhone that was handed its name, and the session is the only diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 927d5df07..898ccb679 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -74,7 +74,16 @@ false and every request is refused. (`cannot_host`); one holding a link with another peer answers `close` (`busy`). One that already offered this peer a link sends the same offer again, since the request means the first one was lost. Otherwise it starts hosting under -the request's link id. +the request's link id, unless two links it hosted in a row for that peer's +requests expired with no stream from the peer: then it answers `busy` for ten +minutes, so a peer that never joins cannot keep a group on the air, and the +device's own group formation locked out, by asking again each time. One miss +is forgiven, so a user who did not tap in time can ask again, and this +device's own request to the peer ends the pause. + +When an offer answers this device's request under a different link id, the +request's id is remembered as ended, so a host that acts on the request late +cannot bring up a second network and prompt the user for it. **An `offer` arrives.** A device that cannot join answers `close` (`cannot_join`), and one holding a link with another peer answers `busy`. For From 152f589ef205df28394915e5d3845db31ca642ea Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:09:55 +0530 Subject: [PATCH 26/81] docs: changelog and permissions for the fast link the unreleased changelog gains the fast link under added and the 16-chunk peer-stream window under changed, and the mobile permissions guide says what an integrator needs: the hotspot configuration entitlement and local-network keys on ios, the wi-fi direct grants and android 10 on android, and what the user sees. --- CHANGELOG.md | 25 +++++++++++++++++++++++++ docs/mobile-permissions.md | 20 ++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c60c65211..af2488072 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,23 @@ Questions about a release, or about upgrading to one? Ask in the ### Added +- **Two devices that meet only over Bluetooth can bring up Wi-Fi between + them: the fast link** ([ADR 0038](docs/adr/0038-a-fast-link-is-offered-inside-the-session.md)). + `requestFastLink(peer)` (React Native and Flutter; `request_fast_link` over + the FFI) asks a peer with a confirmed session for a Wi-Fi network: an + Android device hosts a Wi-Fi Direct group with fresh random credentials, + sealed to the peer in the session, and an iPhone joins it after a system + prompt. The stream over it fills the peer-stream slot, so transfers move to + it on their own: a 1 MiB file that took 197.7 s over Bluetooth took about + 2.5 s on two phones. Progress arrives as `fast_link_changed` events; the + link ends after 60 s with nothing large to carry, when the iPhone app leaves + the foreground, or on `closeFastLink`. An iOS app needs the Hotspot + Configuration entitlement, and an Android app `NEARBY_WIFI_DEVICES` (fine + location below Android 13); see [mobile permissions](docs/mobile-permissions.md#fast-link). + Platforms declare what they can do through four new peer-stream driver + calls, `wifi_direct_set_fast_link_roles` and its siblings; a custom + platform that declares nothing is never asked to host or join. + - **Native iOS and Android applications get the SDK's built-in storage.** `OfflineProtocolReferenceStorage` opens the Keychain or Keystore MLS store and the app-container protocol-state store for one `(appId, profile)` account, @@ -76,6 +93,14 @@ Questions about a release, or about upgrading to one? Ask in the automated publishing. The first version is uploaded by hand ([docs/flutter-distribution.md](docs/flutter-distribution.md)). +### Changed + +- **A file transfer over a peer stream keeps 16 chunks in flight, not 4.** + Every peer-stream carrier gets it (a fast link, a Wi-Fi Direct group, a LAN, + AWDL): with four, a 1 MiB file over a fast link took 8 s waiting on + acknowledgements rather than on the link. Bluetooth, internet and Nostr + windows are unchanged. + ### Fixed - **Flutter on Android now reports a lost MLS identity.** Its engine host diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index e9d88328d..771db05c3 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -128,6 +128,26 @@ iOS expects: The system may prompt on first use. Enable the Wi‑Fi / peer-stream slot in config only when you are ready to show that flow. +### Fast link + +`requestFastLink` ([ADR 0038](adr/0038-a-fast-link-is-offered-inside-the-session.md)) +brings up a Wi-Fi network between this device and a peer it meets over +Bluetooth. An iPhone joins the network the peer hosts, which needs the +**Hotspot Configuration** capability: add +`com.apple.developer.networking.HotspotConfiguration` to the app's +entitlements (Xcode adds it to the App ID with automatic signing), and keep +the local-network keys above, since the stream is a local-network connection. +Without the entitlement every join ends `failed`. + +iOS shows "“App” Wants to Join Wi‑Fi Network “DIRECT-…”?" on every join, and +the phone leaves its own Wi-Fi while the link lasts. Ask for a link when a +transfer is worth that to your user. The link ends when the app leaves the +foreground. + +On Android the fast link uses the Wi-Fi Direct permissions below +(`NEARBY_WIFI_DEVICES` on 13+, fine location on 12 and lower) and needs +Android 10 or later; no prompt is shown. + ### iOS native (Swift package / XCFramework) The same `Info.plist` rules apply. Native hosts do not get permission prompts from From 605ebdd4f5e4fc68279dfe72c0116c30e06ec04a Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:11:02 +0530 Subject: [PATCH 27/81] docs(sealed): say the leaf advertises no fast link today the fast_link prefix comment said a leaf with a wi-fi radio can host or join a link, while the capability chapter and the leaf's key package say a leaf advertises nothing and is never offered one. the comment now agrees. --- crates/offline-protocol-sealed/src/prefixes.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol-sealed/src/prefixes.rs b/crates/offline-protocol-sealed/src/prefixes.rs index e9da6efa6..d56b0039e 100644 --- a/crates/offline-protocol-sealed/src/prefixes.rs +++ b/crates/offline-protocol-sealed/src/prefixes.rs @@ -78,8 +78,10 @@ pub const MEMBER: &str = "__MEMBER__"; /// /// Inside, because an offer carries a passphrase: MLS hides it, names the /// sender and refuses a replayed ciphertext, and a control-plane signature -/// would do only the second. It is a pair's frame like the others here, and a -/// leaf with a Wi-Fi radio can host or join a link as well as a phone can. +/// would do only the second. It is a pair's frame like the others here: a +/// device built on this crate with a Wi-Fi radio could host or join a link, +/// though the leaf crate advertises no `link_versions` today and so is never +/// offered one. pub const FAST_LINK: &str = "__FAST_LINK__"; #[cfg(test)] From 8ed3f411f960360c7e65f5b1a45678c427b3a640 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:22:31 +0530 Subject: [PATCH 28/81] fix(bindings): regenerate the c# local api and the rn bridge adapters the c# sdk's generated local api lacked the six fast-link calls, and the two react native adapters had requestFastLink and closeFastLink placed by hand where their generators sort them otherwise, so gen_csharp_local_api.py and check-binding-generators.sh failed their --check. both are regenerated; the c# suite was not run here (no dotnet). --- bindings/csharp/local_api_methods.txt | 6 +++++ .../OfflineProtocol.Sdk/Generated/Enums.g.cs | 2 +- .../Generated/LocalApiClients.g.cs | 2 +- .../Generated/ProtocolConfig.g.cs | 2 +- .../ProtocolEngine.LocalApi.part01.g.cs | 8 +++---- .../ProtocolEngine.LocalApi.part02.g.cs | 14 +++++------ .../ProtocolEngine.LocalApi.part03.g.cs | 20 +++++++++++++++- .../Generated/ProtocolEngine.Static.g.cs | 2 +- .../ProtocolEngineHostBridgeReactNative.kt | 24 +++++++++---------- .../ProtocolEngineHostBridgeReactNative.swift | 24 +++++++++---------- 10 files changed, 64 insertions(+), 40 deletions(-) diff --git a/bindings/csharp/local_api_methods.txt b/bindings/csharp/local_api_methods.txt index a0f018fbe..ab7375373 100644 --- a/bindings/csharp/local_api_methods.txt +++ b/bindings/csharp/local_api_methods.txt @@ -16,6 +16,7 @@ ble_undersized_mtu_reports block_user cancel_connection_request cancel_file_transfer +close_fast_link close_file_stores create_group create_invite @@ -146,6 +147,7 @@ release_transport_lock remove_from_group remove_transport rename_group +request_fast_link request_group_relay_registration resolve_username resume @@ -209,8 +211,12 @@ update_transport_metrics verify_identity_assertion verify_signature verify_signature_bytes +wifi_direct_fast_link_ended +wifi_direct_fast_link_hosting wifi_direct_get_next_message wifi_direct_message_received +wifi_direct_next_fast_link_directive wifi_direct_peer_connected wifi_direct_peer_disconnected +wifi_direct_set_fast_link_roles wifi_direct_status_changed diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index 7a98c238b..517f34334 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index befee7ac4..e7c96dc9b 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index 9015eadf1..577a742df 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index b52a91da6..d1a227821 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable @@ -66,6 +66,9 @@ public Task CancelConnectionRequestAsync(string? parametersJson = null, public Task CancelFileTransferAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("cancel_file_transfer", parametersJson, cancellationToken); + public Task CloseFastLinkAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallWithResultAsync("close_fast_link", parametersJson, cancellationToken); + public Task CloseFileStoresAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("close_file_stores", parametersJson, cancellationToken); @@ -248,7 +251,4 @@ public Task ListGroupsAsync(string? parametersJson = null, CancellationT public Task MlsClearPendingWelcomeAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("mls_clear_pending_welcome", parametersJson, cancellationToken); - - public Task MlsCreateSessionAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => - CallWithResultAsync("mls_create_session", parametersJson, cancellationToken); } diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index d5f8afe5d..61c76261e 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable @@ -12,6 +12,9 @@ namespace OfflineProtocol.Sdk; public sealed partial class ProtocolEngine { + public Task MlsCreateSessionAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallWithResultAsync("mls_create_session", parametersJson, cancellationToken); + public Task MlsDecryptAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallWithResultAsync("mls_decrypt", parametersJson, cancellationToken); @@ -123,6 +126,9 @@ public Task RemoveTransportAsync(string? parametersJson = null, CancellationToke public Task RenameGroupAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("rename_group", parametersJson, cancellationToken); + public Task RequestFastLinkAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallWithResultAsync("request_fast_link", parametersJson, cancellationToken); + public Task RequestGroupRelayRegistrationAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallWithResultAsync("request_group_relay_registration", parametersJson, cancellationToken); @@ -245,10 +251,4 @@ public Task UpdateDorsConfigAsync(string? parametersJson = null, CancellationTok public Task UpdateRelayConfigAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("update_relay_config", parametersJson, cancellationToken); - - public Task UpdateRetryConfigAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => - CallAsync("update_retry_config", parametersJson, cancellationToken); - - public Task UpdateTransportMetricsAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => - CallAsync("update_transport_metrics", parametersJson, cancellationToken); } diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 68099b7c7..44d637695 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable @@ -12,24 +12,42 @@ namespace OfflineProtocol.Sdk; public sealed partial class ProtocolEngine { + public Task UpdateRetryConfigAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallAsync("update_retry_config", parametersJson, cancellationToken); + + public Task UpdateTransportMetricsAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallAsync("update_transport_metrics", parametersJson, cancellationToken); + public Task VerifySignatureAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallWithResultAsync("verify_signature", parametersJson, cancellationToken); public Task VerifySignatureBytesAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallWithResultAsync("verify_signature_bytes", parametersJson, cancellationToken); + public Task WifiDirectFastLinkEndedAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallAsync("wifi_direct_fast_link_ended", parametersJson, cancellationToken); + + public Task WifiDirectFastLinkHostingAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallAsync("wifi_direct_fast_link_hosting", parametersJson, cancellationToken); + public Task WifiDirectGetNextMessageAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallWithResultAsync("wifi_direct_get_next_message", parametersJson, cancellationToken); public Task WifiDirectMessageReceivedAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("wifi_direct_message_received", parametersJson, cancellationToken); + public Task WifiDirectNextFastLinkDirectiveAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallWithResultAsync("wifi_direct_next_fast_link_directive", parametersJson, cancellationToken); + public Task WifiDirectPeerConnectedAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("wifi_direct_peer_connected", parametersJson, cancellationToken); public Task WifiDirectPeerDisconnectedAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("wifi_direct_peer_disconnected", parametersJson, cancellationToken); + public Task WifiDirectSetFastLinkRolesAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => + CallAsync("wifi_direct_set_fast_link_roles", parametersJson, cancellationToken); + public Task WifiDirectStatusChangedAsync(string? parametersJson = null, CancellationToken cancellationToken = default) => CallAsync("wifi_direct_status_changed", parametersJson, cancellationToken); } diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index 2991130fd..3a17ce030 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 // Do not edit. #nullable enable diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt index ecc112237..e1fd974cb 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHostBridgeReactNative.kt @@ -68,18 +68,6 @@ fun bleGetPeerCount(module: OfflineProtocolModule, promise: Promise) { } } -fun requestFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { - run(module, promise, "ERROR_FAST_LINK", "Failed to request a fast link", mapProtocolErrors = true) { host, context -> - ProtocolEngineHostBridge.requestFastLink(host, context, mapOf("peerId" to peerId)) - } -} - -fun closeFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { - run(module, promise, "ERROR_FAST_LINK", "Failed to close the fast link") { host, context -> - ProtocolEngineHostBridge.closeFastLink(host, context, mapOf("peerId" to peerId)) - } -} - fun blockUser(module: OfflineProtocolModule, userId: String, promise: Promise) { run(module, promise, "ERROR_BLOCK_USER", "Failed to block user") { host, context -> ProtocolEngineHostBridge.blockUser(host, context, mapOf("userId" to userId)) @@ -110,6 +98,12 @@ fun clearServiceTopic(module: OfflineProtocolModule, serviceId: String, topic: S } } +fun closeFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { + run(module, promise, "ERROR_FAST_LINK", "Failed to close the fast link") { host, context -> + ProtocolEngineHostBridge.closeFastLink(host, context, mapOf("peerId" to peerId)) + } +} + fun createInvite(module: OfflineProtocolModule, petname: String?, signed: Boolean, promise: Promise) { run(module, promise, "ERROR_NOT_INITIALIZED", "Protocol not initialized") { host, context -> ProtocolEngineHostBridge.createInvite(host, context, mapOf("petname" to petname, "signed" to signed)) @@ -536,6 +530,12 @@ fun requestEnableBluetooth(module: OfflineProtocolModule, promise: Promise) { } } +fun requestFastLink(module: OfflineProtocolModule, peerId: String, promise: Promise) { + run(module, promise, "ERROR_FAST_LINK", "Failed to request a fast link", mapProtocolErrors = true) { host, context -> + ProtocolEngineHostBridge.requestFastLink(host, context, mapOf("peerId" to peerId)) + } +} + fun resolveUsername(module: OfflineProtocolModule, username: String, promise: Promise) { run(module, promise, "ERROR_INVALID_ARGUMENT", "Failed to resolve username", mapProtocolErrors = true) { host, context -> ProtocolEngineHostBridge.resolveUsername(host, context, mapOf("username" to username)) diff --git a/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift b/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift index 845995028..87fc4b516 100644 --- a/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift +++ b/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift @@ -63,18 +63,6 @@ enum ProtocolEngineHostBridgeReactNative { } } - static func requestFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { - run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to request a fast link", mapProtocolErrors: true) { host, env in - try ProtocolEngineHostBridge.requestFastLink(host: host, env: env, arguments: ["peerId": peerId]) - } - } - - static func closeFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { - run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to close the fast link") { host, env in - try ProtocolEngineHostBridge.closeFastLink(host: host, env: env, arguments: ["peerId": peerId]) - } - } - static func blockUser(_ module: OfflineProtocolModule, _ userId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_BLOCK_USER", errorMessage: "Failed to block user") { host, env in try ProtocolEngineHostBridge.blockUser(host: host, env: env, arguments: ["userId": userId]) @@ -105,6 +93,12 @@ enum ProtocolEngineHostBridgeReactNative { } } + static func closeFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { + run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to close the fast link") { host, env in + try ProtocolEngineHostBridge.closeFastLink(host: host, env: env, arguments: ["peerId": peerId]) + } + } + static func createInvite(_ module: OfflineProtocolModule, _ petname: String?, sign signed: NSNumber, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_NOT_INITIALIZED", errorMessage: "Protocol not initialized") { host, env in try ProtocolEngineHostBridge.createInvite(host: host, env: env, arguments: ["petname": petname, "signed": signed]) @@ -531,6 +525,12 @@ enum ProtocolEngineHostBridgeReactNative { } } + static func requestFastLink(_ module: OfflineProtocolModule, _ peerId: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { + run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_FAST_LINK", errorMessage: "Failed to request a fast link", mapProtocolErrors: true) { host, env in + try ProtocolEngineHostBridge.requestFastLink(host: host, env: env, arguments: ["peerId": peerId]) + } + } + static func resolveUsername(_ module: OfflineProtocolModule, _ username: String, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) { run(module, resolver: resolver, rejecter: rejecter, errorCode: "ERROR_INVALID_ARGUMENT", errorMessage: "Failed to resolve username", mapProtocolErrors: true) { host, env in try ProtocolEngineHostBridge.resolveUsername(host: host, env: env, arguments: ["username": username]) From b178958666ec060c28efd8e35c235bcb521ddb01 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:24:35 +0530 Subject: [PATCH 29/81] fix(protocol): a peer that closes its unused links cannot dodge the host backoff the host counted only links that expired toward its request backoff, so a peer could close each link with any other reason just before it expired and ask again, holding the android's one group on the air for as long as it liked. an unused link the peer ended now counts too, whatever its reason; ends this device caused do not. --- crates/offline-protocol/src/fast_link.rs | 72 ++++++++++++++++++++++-- docs/state-machines/fast-link.md | 4 +- 2 files changed, 69 insertions(+), 7 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 97195b688..c69d2e928 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -965,14 +965,25 @@ impl FastLinks { } /// Counts a link hosted for `peer`'s request that ended: one its stream - /// used resets the count, one that expired unused adds to it, and - /// [`MAX_UNANSWERED_HOSTINGS`] in a row start [`HOST_BACKOFF`]. - fn count_hosting(&mut self, peer: &str, used: bool, reason: CloseReason, now: Instant) { + /// used resets the count; one that went unused adds to it when it expired + /// or the peer ended it, whatever reason the peer gave; and + /// [`MAX_UNANSWERED_HOSTINGS`] in a row start [`HOST_BACKOFF`]. Ends this + /// device caused (its platform failing, its tie-break, its user) are not + /// the peer's to answer for. Counting only `expired` let a peer close + /// each link just before it expired and ask again, forever. + fn count_hosting( + &mut self, + peer: &str, + used: bool, + by_peer: bool, + reason: CloseReason, + now: Instant, + ) { if used { self.unanswered.retain(|(unanswered, _)| unanswered != peer); return; } - if reason != CloseReason::Expired { + if !by_peer && reason != CloseReason::Expired { return; } let count = match self.unanswered.iter_mut().find(|(p, _)| p == peer) { @@ -1036,7 +1047,13 @@ impl FastLinks { .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); if link.role == FastLinkRole::Host && link.requested_by_peer { - self.count_hosting(&link.peer, link.state == FastLinkState::Up, reason, now); + self.count_hosting( + &link.peer, + link.state == FastLinkState::Up, + !tell_peer, + reason, + now, + ); } if link.role == FastLinkRole::Join { if self.ended_joins.len() >= MAX_ENDED_REMEMBERED { @@ -2068,6 +2085,51 @@ mod tests { ); } + #[test] + fn a_peer_cannot_dodge_the_host_backoff_by_closing_first() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let round = |android: &mut FastLinks, seed: u8| { + let id = fresh(seed).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(seed + 1), + t0, + 0, + ); + let hosted = android.next_directive(t0).map(|d| d.kind); + if hosted.is_some() { + android.hosting(&id, "192.168.49.1", 8988, t0, 0); + // The peer closes just before the offer would expire. + android.on_frame( + HIGH, + LOW, + Frame::new( + &id, + FrameBody::Close { + reason: "closed".to_string(), + }, + ), + fresh(seed + 2), + t0, + 0, + ); + android.next_directive(t0); + } + android.take_frames(); + hosted + }; + assert!(round(&mut android, 1).is_some()); + assert!(round(&mut android, 4).is_some()); + assert_eq!( + round(&mut android, 7), + None, + "two unused links the peer ended: refused" + ); + } + #[test] fn a_superseded_request_cannot_be_hosted_into_a_prompt_later() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 898ccb679..c042e3b04 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -75,8 +75,8 @@ false and every request is refused. One that already offered this peer a link sends the same offer again, since the request means the first one was lost. Otherwise it starts hosting under the request's link id, unless two links it hosted in a row for that peer's -requests expired with no stream from the peer: then it answers `busy` for ten -minutes, so a peer that never joins cannot keep a group on the air, and the +requests went unused, expiring or ended by the peer (whatever reason it gives) +with no stream from it: then it answers `busy` for ten minutes, so a peer that never joins cannot keep a group on the air, and the device's own group formation locked out, by asking again each time. One miss is forgiven, so a user who did not tap in time can ask again, and this device's own request to the peer ends the pause. From 0f018b2db2babdb24bc0d8883b7a73002f318740 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:25:37 +0530 Subject: [PATCH 30/81] fix(protocol): only a transfer on the link holds it off the idle limit any outbound transfer to the peer held the link open, but a transfer's carrier is fixed when it starts, so one begun over bluetooth before the link came up never moved to it, and the iphone stayed off its own wi-fi while the link carried nothing. only a transfer pinned to the peer-stream slot holds the link now, and the request docs say to send after the link is up. --- bindings/react-native/src/index.ts | 4 ++- .../src/protocol/fast_link.rs | 21 +++++++++--- .../src/protocol/tests/fast_link.rs | 32 +++++++++++++++++++ docs/state-machines/fast-link.md | 4 ++- 4 files changed, 55 insertions(+), 6 deletions(-) diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index d5c747878..81d2f4792 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4608,7 +4608,9 @@ export class OfflineProtocol { * device hosts (an Android phone) and the other joins, with credentials * sealed in the session, and traffic moves onto the link by ordinary * transport selection: a 1 MiB file that takes minutes over Bluetooth takes - * seconds over it. + * seconds over it. A file transfer keeps the carrier it started on, so send + * after the `fast_link_changed` event with state `up` for it to use the + * link. * * Resolves with the link id as soon as the first step is taken; the outcome * arrives as `fast_link_changed` events. On iOS the join shows a system diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index fea9119f8..2c980a1d2 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -176,13 +176,26 @@ impl OfflineProtocol { if self.fast_links.peer().is_none() { return; } - let outbound = &self.outbound_media_transfers; - self.fast_links.tick(Instant::now(), |peer| { - outbound.values().any(|transfer| transfer.recipient == peer) - }); + let busy: std::collections::HashSet = self + .outbound_media_transfers + .values() + .filter(|transfer| Self::holds_fast_link(transfer)) + .map(|transfer| transfer.recipient.clone()) + .collect(); + self.fast_links + .tick(Instant::now(), |peer| busy.contains(peer)); self.flush_fast_link(); } + /// Whether an outbound transfer holds its recipient's fast link off the + /// idle limit: only one pinned to the peer-stream slot. A transfer's + /// carrier is fixed when it starts, so one begun over Bluetooth before + /// the link came up never moves to it, and holding the link for it kept + /// an iPhone off its own Wi-Fi for nothing. + pub(crate) fn holds_fast_link(transfer: &super::types::OutboundMediaTransfer) -> bool { + transfer.pinned_transport == TransportType::WiFiDirect + } + /// Whether a peer stream holds `peer` now. fn peer_stream_proves(&self, peer: &str) -> bool { self.transport_manager diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 595282513..7eac9daf0 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -378,3 +378,35 @@ fn blocking_a_peer_ends_its_fast_link() { &("closed".to_string(), Some("closed".to_string())) ); } + +/// A transfer started over Bluetooth before the link came up stays on +/// Bluetooth, so it does not hold the link off its idle limit; one pinned to +/// the peer-stream slot does. +#[test] +fn only_a_transfer_on_the_peer_stream_holds_the_link() { + use offline_protocol_core::ContentType; + + let (mut alice, bob) = pair(); + alice + .protocol + .send_media( + &bob.address, + vec![0x5a; 64 * 1024], + "slow.bin", + ContentType::File, + None, + ) + .unwrap(); + let on_bluetooth = alice + .protocol + .outbound_media_transfers + .values() + .next() + .unwrap(); + assert_eq!(on_bluetooth.pinned_transport, TransportType::BLE); + assert!(!OfflineProtocol::holds_fast_link(on_bluetooth)); + + let mut on_stream = on_bluetooth.clone(); + on_stream.pinned_transport = TransportType::WiFiDirect; + assert!(OfflineProtocol::holds_fast_link(&on_stream)); +} diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index c042e3b04..18f6c014c 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -131,7 +131,9 @@ the reason. The idle limit counts a body of at least 16 KiB carried by the slot in either direction for this peer as activity, and does not run while a file transfer -to the peer is in flight. Smaller bodies (presence, receipts, chat) do not +to the peer is in flight over the link. A transfer's carrier is fixed when it +starts, so one begun over Bluetooth before the link came up stays there and +does not hold the link. Smaller bodies (presence, receipts, chat) do not count: Bluetooth LE carries them well, and on two phones an application's presence update every 15 s held a link up indefinitely when they did. A link that carries nothing large for 60 s is costing the user their own Wi-Fi for From 5ca21cebc52f2f8f7ad50f435c2d11b4196fdd4e Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:37:29 +0530 Subject: [PATCH 31/81] fix(protocol): pausing the engine ends a fast link the link's timers run on the engine's tick, and a paused engine does not tick, so a link paused on an android host kept its group on the air, and the device's own formation locked out, with no bound at all until the app came back. pausing now ends any link with background, telling the peer and this device's platform, which drains a close while paused. --- crates/offline-protocol/src/fast_link.rs | 10 +++++++ .../src/protocol/fast_link.rs | 10 +++++++ crates/offline-protocol/src/protocol/mod.rs | 5 ++++ .../src/protocol/tests/fast_link.rs | 29 +++++++++++++++++++ docs/state-machines/fast-link.md | 4 +++ 5 files changed, 58 insertions(+) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index c69d2e928..18bf6fd43 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -887,6 +887,16 @@ impl FastLinks { true } + /// Ends the link with `peer` for a reason of this device's own, telling + /// the peer. + pub(crate) fn end_for(&mut self, peer: &str, reason: CloseReason, now: Instant) -> bool { + if self.peer() != Some(peer) { + return false; + } + self.end(reason, true, now); + true + } + /// Ends the link with `peer` without telling the peer: this device's user /// blocked it, and nothing more is sent to a blocked peer. pub(crate) fn forget(&mut self, peer: &str, now: Instant) -> bool { diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 2c980a1d2..1e977b91d 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -83,6 +83,16 @@ impl OfflineProtocol { closed } + /// The engine is pausing: any link ends with `background`, the peer and + /// this device's platform told. + pub(crate) fn end_fast_link_on_pause(&mut self) { + if let Some(peer) = self.fast_links.peer().map(str::to_string) { + self.fast_links + .end_for(&peer, CloseReason::Background, Instant::now()); + self.flush_fast_link(); + } + } + /// The user blocked `peer`: its link ends here and on this platform, /// with nothing sent to it. pub(crate) fn end_fast_link_with_blocked(&mut self, peer: &str) { diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index ad18e99c7..c41c88793 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -2435,6 +2435,11 @@ impl OfflineProtocol { } state.state = ProtocolState::Paused; + drop(state); + // A paused engine runs no timers, so a fast link would outlive every + // bound its state machine promises while the host's group stays on + // the air. It ends here, as the iPhone's side already does. + self.end_fast_link_on_pause(); Ok(()) } diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 7eac9daf0..cd15c0348 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -410,3 +410,32 @@ fn only_a_transfer_on_the_peer_stream_holds_the_link() { on_stream.pinned_transport = TransportType::WiFiDirect; assert!(OfflineProtocol::holds_fast_link(&on_stream)); } + +/// Pausing the engine ends a link: a paused engine runs no timers, so an +/// Android host's group would otherwise stay up until the app returned. +#[test] +fn pausing_the_engine_ends_a_link() { + let (mut alice, mut bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + bob.deliver(alice.take_sent()); + + alice.protocol.pause().unwrap(); + let close = alice.protocol.next_fast_link_directive().unwrap(); + assert_eq!(close.kind, FastLinkDirectiveKind::Close); + assert_eq!( + alice.link_states().last().unwrap(), + &("closed".to_string(), Some("background".to_string())) + ); + // The peer is told, so its half ends too. + bob.protocol.next_fast_link_directive(); + bob.deliver(alice.take_sent()); + assert_eq!( + bob.link_states().last().unwrap(), + &("closed".to_string(), Some("background".to_string())) + ); +} diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 18f6c014c..0ed022db8 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -139,6 +139,10 @@ presence update every 15 s held a link up indefinitely when they did. A link that carries nothing large for 60 s is costing the user their own Wi-Fi for no reason. +Pausing the engine ends a link with `background`: a paused engine runs none +of these timers, and a host's group would otherwise stay on the air until the +application returned, with nothing bounding it. + A joiner's platform that is about to lose the network reports it as `ended` first: on iOS, leaving the foreground, after which iOS disconnects at 15 s whatever the engine thinks. Without the report the host learns from TCP From ee814fee3e7a0c68c71be595fa7de3c43f79c0ea Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:38:44 +0530 Subject: [PATCH 32/81] fix(protocol): a hosting link's passphrase is redacted in debug the link held its network name and passphrase as a plain tuple under a derived debug, so formatting the machine printed the passphrase. they are now held in a type whose debug redacts it, and the test formats a machine holding a link that has not offered yet. --- crates/offline-protocol/src/fast_link.rs | 27 +++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 18bf6fd43..162c9fcee 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -474,6 +474,21 @@ struct PendingDirective { deadline: Option, } +/// A network name and passphrase held by a link. Its `Debug` never prints +/// the passphrase, so neither does the derived `Debug` of [`Link`] or +/// [`FastLinks`] (invariant 5). +#[derive(Clone)] +struct Credentials(String, String); + +impl fmt::Debug for Credentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Credentials") + .field(&self.0) + .field(&"[REDACTED]") + .finish() + } +} + #[derive(Debug, Clone)] struct Link { id: String, @@ -484,7 +499,7 @@ struct Link { deadline: Option, last_activity: Instant, /// The host's credentials, until the offer is made. - credentials: Option<(String, String)>, + credentials: Option, /// The host's offer, kept to answer a repeated request. offer: Option, /// The platform drained a directive for this link, so its end needs a @@ -607,7 +622,7 @@ impl FastLinks { state: FastLinkState::Hosting, deadline: Some(now + HOSTING_TIMEOUT), last_activity: now, - credentials: Some((fresh.ssid, fresh.passphrase)), + credentials: Some(Credentials(fresh.ssid, fresh.passphrase)), offer: None, platform_engaged: false, peer_engaged, @@ -641,7 +656,7 @@ impl FastLinks { let Some(link) = self.link.as_mut() else { return false; }; - let Some((ssid, passphrase)) = link.credentials.take() else { + let Some(Credentials(ssid, passphrase)) = link.credentials.take() else { return false; }; let offer = Offer { @@ -1226,6 +1241,12 @@ mod tests { assert_ne!(fresh(7).passphrase, fresh(8).passphrase); let shown = format!("{link:?}"); assert!(!shown.contains(&link.passphrase), "{shown}"); + + // Nor the machine holding a link that has not offered yet. + let mut host = machine(host_roles()); + host.request(HIGH, link.clone(), Instant::now()).unwrap(); + let shown = format!("{host:?}"); + assert!(!shown.contains(&link.passphrase), "{shown}"); } #[test] From b8653f14548ab5e48f77211db42000056c012999 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:38:44 +0530 Subject: [PATCH 33/81] docs: say where an android joiner dials, and the window-16 speed the adr, the state machine and r34 said the joiner dials the offered host. an android joiner dials the group owner's own address instead, because it stays on its own wi-fi and an offered private address could name a host on the home network; the docs now say so and why. the adr's speed consequence gives the measured 2.5 s against bluetooth's 197.7 s. --- .../0038-a-fast-link-is-offered-inside-the-session.md | 11 ++++++++--- docs/security/threat-model.md | 4 +++- docs/state-machines/fast-link.md | 2 +- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 2c991d183..1b818b507 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -85,7 +85,11 @@ the foreground and deleted the passphrase. (step four of the preamble). The host refuses, on the network it made, any proved address other than the one it invited. The offered address must be a private or link-local IP literal: never a name to resolve, never a route - off the network just joined. + off the network just joined. An iPhone dials it bound to Wi-Fi, having + left its own network for the group. An Android joiner stays on its own + Wi-Fi while in a group, so an offered private address could name a host on + the user's home network: it dials the group owner's address as the group + reports it, with the offer's port, and never the offer's host. 7. **The engine ends a link** when its offer expires unused (120 s), when the proved stream is lost, after 60 s with nothing large carried (a body of @@ -125,8 +129,9 @@ session, and only uses it. ## Consequences -- An iPhone and an Android phone with no shared network move a file about 20 - times faster than over Bluetooth, after one prompt on the iPhone. A message +- An iPhone and an Android phone with no shared network move a 1 MiB file in + about 2.5 s instead of 197.7 s over Bluetooth, after one prompt on the + iPhone (8 s before decision 9). A message too large for Bluetooth fits the slot's 1 MiB ceiling. - The join takes the iPhone off its own Wi-Fi for as long as the link lasts, and the link lasts only while the application is in the foreground. An diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index d127a228c..801763f08 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1478,7 +1478,9 @@ the host's address and can hand them on, and a peer that shares a session can already send anything. A hostile session peer can offer a network it controls and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial -is bound to the Wi-Fi interface, and the stream must prove the offerer's own +stays on the group (an iPhone binds it to Wi-Fi; an Android, which keeps its +own Wi-Fi, dials the group owner's address and not the offer's), and the +stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most 300 s later. It can also put the iOS join prompt in front of a user who did not ask: an offer needs no request. Once the user declines, that peer's diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 0ed022db8..c7cfacd44 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -45,7 +45,7 @@ wake-up that drains outbound stream bodies: | Directive | The platform | Then reports | |-----------|--------------|--------------| | `host` | Brings up a network with the given name and passphrase, admitting the given peer only | `wifi_direct_fast_link_hosting(link, host, port)`, or `wifi_direct_fast_link_ended(link, reason)` | -| `join` | Joins the given network and dials `host:port`, claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | +| `join` | Joins the given network and dials `host:port` (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | | `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | A platform declares what it can do with From 63fc77194553249b838ac3e17324617150577571 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:52:11 +0530 Subject: [PATCH 34/81] fix(protocol): grow the peer-stream window in bytes, not ratchet generations a window of 16 chunks let two transfers to one peer put 32 chunks in flight, the receiver's whole out-of-order tolerance on the 1:1 ratchet, with nothing left for messages interleaved with them, and the constants that budget it said so. the peer-stream slot now keeps the same 512 KiB in flight as eight 64 KiB chunks, which leaves half the tolerance free, and a compile-time check ties every carrier's window to the tolerance so raising one fails the build. --- CHANGELOG.md | 11 ++-- crates/offline-protocol/src/constants.rs | 51 +++++++++++++++---- crates/offline-protocol/src/protocol/send.rs | 4 +- .../src/protocol/tests/fast_link.rs | 19 ++++--- ...fast-link-is-offered-inside-the-session.md | 11 ++-- 5 files changed, 69 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af2488072..a9a65a5b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,11 +95,12 @@ Questions about a release, or about upgrading to one? Ask in the ### Changed -- **A file transfer over a peer stream keeps 16 chunks in flight, not 4.** - Every peer-stream carrier gets it (a fast link, a Wi-Fi Direct group, a LAN, - AWDL): with four, a 1 MiB file over a fast link took 8 s waiting on - acknowledgements rather than on the link. Bluetooth, internet and Nostr - windows are unchanged. +- **A file transfer over a peer stream keeps 512 KiB in flight, not 128 KiB:** + eight 64 KiB chunks instead of four of 32 KiB. Every peer-stream carrier + gets it (a fast link, a Wi-Fi Direct group, a LAN, AWDL): with the old + window, a 1 MiB file over a fast link took 8 s waiting on acknowledgements + rather than on the link. Bluetooth, internet and Nostr windows are + unchanged. ### Fixed diff --git a/crates/offline-protocol/src/constants.rs b/crates/offline-protocol/src/constants.rs index d957c726b..a3c620d3f 100644 --- a/crates/offline-protocol/src/constants.rs +++ b/crates/offline-protocol/src/constants.rs @@ -128,16 +128,28 @@ pub const MEDIA_WINDOW_SIZE_INTERNET: usize = 8; /// Default maximum chunks in flight for media transfers. pub const DEFAULT_MEDIA_WINDOW_SIZE: usize = 4; -/// Maximum chunks in flight for media transfers on the peer-stream slot (a -/// Wi-Fi Direct group, a LAN, AWDL or a fast link). +/// Chunk size for media transfers on the peer-stream slot (a Wi-Fi Direct +/// group, a LAN, AWDL or a fast link): 64 KiB. /// -/// Sixteen 32 KiB chunks, 512 KiB in flight. At the default of four a 1 MiB -/// file over a fast link took 8.0 to 8.7 s on two phones (ADR 0038): about -/// 128 KiB per acknowledgement round, with receipts coalesced for up to -/// 500 ms, so the transfer waited on acknowledgements rather than on the link. -/// The platform managers queue up to 4 MiB per stream before dropping, so -/// the window stays well inside what a stream holds. -pub const MEDIA_WINDOW_SIZE_PEER_STREAM: usize = 16; +/// Larger than the default so that the bytes in flight grow without the +/// chunks in flight growing: each chunk is a generation of the 1:1 session +/// ratchet, and the receiver keeps only +/// `SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE` (32) of them for late arrivals +/// (see [`MAX_CONCURRENT_MEDIA_TRANSFERS_PER_PEER`]). +pub const CHUNK_SIZE_PEER_STREAM: usize = 64 * 1024; + +/// Maximum chunks in flight for media transfers on the peer-stream slot. +/// +/// Eight 64 KiB chunks, 512 KiB in flight. At four 32 KiB chunks a 1 MiB file +/// over a fast link took 8.0 to 8.7 s on two phones (ADR 0038): about 128 KiB +/// per acknowledgement round, with receipts coalesced for up to 500 ms, so +/// the transfer waited on acknowledgements rather than on the link. The +/// window is eight and not more because it counts ratchet generations: two +/// transfers to one peer at eight leave half the receiver's out-of-order +/// tolerance for everything else on the session, which a window of sixteen +/// used up entirely. The platform managers queue up to 4 MiB per stream +/// before dropping, so 512 KiB stays well inside what a stream holds. +pub const MEDIA_WINDOW_SIZE_PEER_STREAM: usize = 8; /// Maximum entries in the dedicated media outbox. /// Smaller than the main outbox since the sliding window limits in-flight chunks. @@ -164,8 +176,29 @@ pub const MAX_MEDIA_DESCRIPTORS: usize = 16; /// receiver surfaces this as `MessageDecryptionFailed`). Without this cap, /// concurrent transfers alone could push a delayed chunk beyond the /// tolerance and permanently stall its transfer. +/// +/// The bound holds for every carrier's window, and a compile-time check below +/// keeps it: a window raised past half the tolerance, divided across the +/// concurrent transfers, fails the build rather than a transfer. pub const MAX_CONCURRENT_MEDIA_TRANSFERS_PER_PEER: usize = 2; +// Two concurrent transfers at the largest window must leave at least half the +// receiver's out-of-order tolerance free for interleaved messages. +const _: () = { + let tolerance = offline_protocol_sealed::SENDER_RATCHET_OUT_OF_ORDER_TOLERANCE as usize; + let windows = [ + MEDIA_WINDOW_SIZE_BLE, + MEDIA_WINDOW_SIZE_INTERNET, + DEFAULT_MEDIA_WINDOW_SIZE, + MEDIA_WINDOW_SIZE_PEER_STREAM, + ]; + let mut i = 0; + while i < windows.len() { + assert!(MAX_CONCURRENT_MEDIA_TRANSFERS_PER_PEER * windows[i] * 2 <= tolerance); + i += 1; + } +}; + /// The receiver's forward window has to sit well above the number of /// messages this engine keeps in flight to one peer. /// diff --git a/crates/offline-protocol/src/protocol/send.rs b/crates/offline-protocol/src/protocol/send.rs index 0360df698..dd6ffb4a2 100644 --- a/crates/offline-protocol/src/protocol/send.rs +++ b/crates/offline-protocol/src/protocol/send.rs @@ -2896,8 +2896,8 @@ impl OfflineProtocol { (CHUNK_SIZE_INTERNET, MEDIA_WINDOW_SIZE_INTERNET) } TransportType::WiFiDirect => { - use crate::constants::{DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM}; - (DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM) + use crate::constants::{CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM}; + (CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM) } TransportType::Reticulum => { // Reticulum is low-bandwidth (LoRa); use BLE-like chunk sizes. diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index cd15c0348..dc8f134f9 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -271,15 +271,17 @@ fn a_peer_that_cannot_host_says_so() { ); } -/// A transfer pinned to the peer-stream slot leaves sixteen chunks before it -/// waits for an acknowledgement, not four: at four, a fast link spent its -/// time waiting on receipts rather than on the link (ADR 0038, decision 9). +/// A transfer pinned to the peer-stream slot leaves eight 64 KiB chunks before +/// it waits for an acknowledgement, 512 KiB, not four of 32 KiB: at that, a +/// fast link spent its time waiting on receipts rather than on the link (ADR +/// 0038, decision 9). Eight and not more, because each chunk is a ratchet +/// generation. #[test] -fn a_transfer_on_the_peer_stream_slot_fills_a_window_of_sixteen() { +fn a_transfer_on_the_peer_stream_slot_keeps_512_kib_in_flight() { use offline_protocol_core::ContentType; use offline_protocol_transport::PeerLink; - use crate::constants::{DEFAULT_CHUNK_SIZE, MEDIA_WINDOW_SIZE_PEER_STREAM}; + use crate::constants::{CHUNK_SIZE_PEER_STREAM, MEDIA_WINDOW_SIZE_PEER_STREAM}; let (mut alice, bob) = pair(); let stream = MockTransport::new(TransportType::WiFiDirect); @@ -291,7 +293,7 @@ fn a_transfer_on_the_peer_stream_slot_fills_a_window_of_sixteen() { .add_transport(TransportType::WiFiDirect, Box::new(stream.clone())); alice.take_sent(); - let file = vec![0x5a; DEFAULT_CHUNK_SIZE * 20]; + let file = vec![0x5a; CHUNK_SIZE_PEER_STREAM * 20]; alice .protocol .send_media(&bob.address, file, "big.bin", ContentType::File, None) @@ -304,7 +306,10 @@ fn a_transfer_on_the_peer_stream_slot_fills_a_window_of_sixteen() { .filter(|message| message.content_type == ContentType::FileChunk) .count(); assert_eq!(chunks, MEDIA_WINDOW_SIZE_PEER_STREAM); - assert_eq!(MEDIA_WINDOW_SIZE_PEER_STREAM, 16); + assert_eq!( + MEDIA_WINDOW_SIZE_PEER_STREAM * CHUNK_SIZE_PEER_STREAM, + 512 * 1024 + ); } /// A fast-link frame goes over Bluetooth LE when the peer is linked there, diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 1b818b507..32a3c506d 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -105,10 +105,13 @@ the foreground and deleted the passphrase. time and an Android device owns at most one Wi-Fi Direct group, so a second request is refused as busy rather than queued. -9. **The media window on the peer-stream slot is 16 chunks, not 4.** With - 32 KiB chunks and a window of 4 the transfer waited on acknowledgements: - about 128 KiB a round, which is what the spike measured (126 KB/s), far - below the link. Every other slot keeps its window. +9. **The peer-stream slot keeps 512 KiB in flight: eight 64 KiB chunks, not + four of 32 KiB.** With four of 32 KiB the transfer waited on + acknowledgements: about 128 KiB a round, which is what the spike measured + (126 KB/s), far below the link. The bytes grow through the chunk size and + not the chunk count because each chunk is a ratchet generation, and the + receiver keeps 32 for late arrivals: two transfers of sixteen would use + them all. Every other slot keeps its window. ### Why not LocalOnlyHotspot as a fallback From 582e64090b0d170ccde2f626327718d9d066ce8f Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:54:06 +0530 Subject: [PATCH 35/81] test(uniffi): pin the fast-link tokens the bridges send the android and ios managers report fast-link ends and branch on directive kinds by string, and the engine reads an unknown reason as failed without a word: a misspelt declined would switch off the decline pause r34 relies on. a guard now reads both managers and holds every reason and kind literal to the engine's own, and c5 counts the set. --- crates/offline-protocol-uniffi/src/lib.rs | 128 ++++++++++++++++++++++ docs/bridges/README.md | 9 +- 2 files changed, 136 insertions(+), 1 deletion(-) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 9d4a4cfbd..b1b3c4223 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20231,6 +20231,134 @@ mod tests { } } + /// The fast-link tokens the bridges hand the engine, and the directive + /// kinds they branch on, are the engine's own (C5). Both cross the FFI as + /// strings, and the engine reads an unknown reason as `failed` without a + /// word: a typo in a bridge's `declined` would switch off the decline + /// pause that threat model R34 bounds iOS join prompts with, and a typo + /// in a kind would ignore that directive. + #[test] + fn fast_link_tokens_in_the_bridges_are_the_engines() { + use offline_protocol::fast_link::{CloseReason, FastLinkDirectiveKind}; + + /// Every string literal inside the parentheses that follow `call`. + fn literals_in_calls(code: &str, call: &str) -> Vec { + let mut found = Vec::new(); + for (at, _) in code.match_indices(call) { + let rest = &code[at + call.len()..]; + let end = rest.find(')').unwrap_or(rest.len()); + found.extend(literals(&rest[..end])); + } + found + } + /// Every string literal in `text`. + fn literals(text: &str) -> Vec { + text.split('"') + .skip(1) + .step_by(2) + .map(str::to_string) + .collect() + } + /// The literal right after each `marker`. + fn literal_after(code: &str, marker: &str) -> Vec { + code.match_indices(marker) + .filter_map(|(at, _)| { + let rest = &code[at + marker.len()..]; + rest.split('"').nth(1).map(str::to_string) + }) + .collect() + } + + let kotlin = + rn_source_code_only("android/src/main/java/com/offlineprotocol/WifiDirectManager.kt"); + let swift = rn_source_code_only("ios/WifiDirectManager.swift"); + + let mut kotlin_reasons = literals_in_calls(&kotlin, "fastLinkEnded("); + kotlin_reasons.sort(); + kotlin_reasons.dedup(); + let mut swift_reasons = literals_in_calls(&swift, "FastLinkEnded("); + swift_reasons.extend(literals_in_calls(&swift, "endFastLink(")); + for line in swift + .lines() + .filter(|l| l.trim_start().starts_with("let reason =")) + { + swift_reasons.extend(literals(line)); + } + swift_reasons.sort(); + swift_reasons.dedup(); + + for (bridge, reasons, must) in [ + ( + "WifiDirectManager.kt", + &kotlin_reasons, + &["background", "failed", "host_failed", "invalid", "lost"][..], + ), + ( + "WifiDirectManager.swift", + &swift_reasons, + &["background", "declined", "failed", "host_failed"][..], + ), + ] { + for reason in reasons.iter() { + assert_eq!( + CloseReason::parse(reason).as_str(), + reason, + "{bridge} reports the fast-link reason {reason:?}, which the engine does not \ + know and reads as `failed`" + ); + } + for expected in must { + assert!( + reasons.iter().any(|r| r == expected), + "{bridge}: the scan found no {expected:?} among {reasons:?}, so it is no \ + longer reading the reasons the bridge sends" + ); + } + } + + let kinds = [ + FastLinkDirectiveKind::Host.as_str(), + FastLinkDirectiveKind::Join.as_str(), + FastLinkDirectiveKind::Close.as_str(), + ]; + let mut kotlin_kinds = literal_after(&kotlin, "directive.kind == "); + kotlin_kinds.extend(literal_after(&kotlin, "directive.kind != ")); + let drain_start = swift + .find("func drainFastLinkDirectives") + .expect("the iOS manager drains fast-link directives"); + let drain_end = swift[drain_start..] + .find("private func joinFastLink") + .map_or(swift.len(), |end| drain_start + end); + let swift_drain = &swift[drain_start..drain_end]; + let mut swift_kinds = literal_after(swift_drain, "case "); + swift_kinds.extend(literal_after(swift_drain, "directive.kind != ")); + for (bridge, found, must) in [ + ( + "WifiDirectManager.kt", + &kotlin_kinds, + &["close", "host", "join"][..], + ), + ( + "WifiDirectManager.swift", + &swift_kinds, + &["close", "join"][..], + ), + ] { + for kind in found.iter() { + assert!( + kinds.contains(&kind.as_str()), + "{bridge} branches on the directive kind {kind:?}, which the engine never sends" + ); + } + for expected in must { + assert!( + found.iter().any(|k| k == expected), + "{bridge}: the scan found no {expected:?} among {found:?}" + ); + } + } + } + #[test] fn react_native_android_wifi_direct_callback_does_not_wait_for_a_manager() { let code = diff --git a/docs/bridges/README.md b/docs/bridges/README.md index 6096f64b1..71fe35948 100644 --- a/docs/bridges/README.md +++ b/docs/bridges/README.md @@ -130,7 +130,7 @@ in the uniffi crate pins the mobile call sites, which no CI job executes. ## C5. Hand-mirrored constants must be pinned in every language Some constants exist in several places no single compiler sees together. -Seventeen sets do today, and they are pinned by **two different** mechanisms, so +Eighteen sets do today, and they are pinned by **two different** mechanisms, so knowing which one you are touching matters. **The relay-answer prefix exemption list** is the canonical example: the core, @@ -165,6 +165,13 @@ it must name all five transports, and the two entry points that take a name used to carry its own three-name copy that defaulted the rest to BLE, so forcing a transport the copy did not know silently forced the radio. +The fast link's tokens are the eighteenth set: the reasons each mobile bridge +reports through `wifi_direct_fast_link_ended` and the directive kinds it +branches on cross the FFI as strings, and the engine reads an unknown reason +as `failed`, so a misspelt `declined` silently switches off the decline pause +the threat model counts on. `fast_link_tokens_in_the_bridges_are_the_engines` +reads both managers and holds each token to the engine's own. + The per-send application id is pinned the same way, by `react_native_rich_sends_carry_the_app_id_end_to_end`. It is optional at every layer, so a layer that omits it compiles and drops it: the TypeScript params From fa212a91fabd8c3afb7cf0a5bf388abd8314760f Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 08:59:48 +0530 Subject: [PATCH 36/81] feat(bindings): let an app choose whether it takes part in a peer's fast link a device hosted for any session peer's request and joined any offer it did not ask for, so a peer's app could put the ios join prompt in front of a user whose own app never asked, or move an android device onto its group without a prompt. wifiDirect.fastLink now decides: any (the default, as before), requestedOnly, which answers a peer's request or unasked-for offer declined, or off. the roles call carries it as accept_unrequested, so every binding, the c dispatcher, the python and c# tables are regenerated, and the adr, state machine, r34, permissions guide and changelog say what each mode does. --- CHANGELOG.md | 7 +- .../OfflineProtocol.Sdk/Generated/Enums.g.cs | 2 +- .../Generated/LocalApiClients.g.cs | 2 +- .../Generated/ProtocolConfig.g.cs | 2 +- .../ProtocolEngine.LocalApi.part01.g.cs | 2 +- .../ProtocolEngine.LocalApi.part02.g.cs | 2 +- .../ProtocolEngine.LocalApi.part03.g.cs | 2 +- .../Generated/ProtocolEngine.Static.g.cs | 2 +- .../offlineprotocol/sdk/NamespaceLibrary.java | 2 +- .../offlineprotocol/sdk/OfflineProtocol.java | 4 +- .../sdk/OfflineProtocolInterface.java | 2 +- .../com/offlineprotocol/sdk/UniffiLib.java | 6 +- .../offline_protocol_sdk/local_api/table.py | 6 +- .../offline_protocol_sdk/offline_protocol.py | 10 ++- .../com/offlineprotocol/ProtocolEngineHost.kt | 4 + .../com/offlineprotocol/WifiDirectManager.kt | 38 +++++++- .../offline_protocol/offline_protocol.kt | 11 +-- .../com/offlineprotocol/FastLinkModeTest.kt | 25 ++++++ .../ios/Generated/offline_protocol.swift | 9 +- .../ios/Generated/offline_protocolFFI.h | 2 +- .../react-native/ios/ProtocolEngineHost.swift | 1 + .../react-native/ios/WifiDirectManager.swift | 34 ++++++- bindings/react-native/src/types.ts | 14 +++ bindings/ruby/lib/offline_protocol.rb | 8 +- .../src/capi/generated.rs | 3 +- crates/offline-protocol-uniffi/src/lib.rs | 9 +- .../src/offline_protocol.udl | 10 ++- crates/offline-protocol/src/fast_link.rs | 88 ++++++++++++++++++- .../src/protocol/fast_link.rs | 17 +++- .../src/protocol/tests/fast_link.rs | 10 +-- ...fast-link-is-offered-inside-the-session.md | 6 +- docs/mobile-permissions.md | 5 +- docs/security/threat-model.md | 4 +- docs/state-machines/fast-link.md | 8 +- 34 files changed, 296 insertions(+), 61 deletions(-) create mode 100644 bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkModeTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index a9a65a5b4..392a96d83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,8 +31,11 @@ Questions about a release, or about upgrading to one? Ask in the the foreground, or on `closeFastLink`. An iOS app needs the Hotspot Configuration entitlement, and an Android app `NEARBY_WIFI_DEVICES` (fine location below Android 13); see [mobile permissions](docs/mobile-permissions.md#fast-link). - Platforms declare what they can do through four new peer-stream driver - calls, `wifi_direct_set_fast_link_roles` and its siblings; a custom + `wifiDirect.fastLink` decides how far an app takes part: `any` (the + default) also hosts for a peer's request and joins an offer it did not ask + for, `requestedOnly` takes part only in links the app asked for, `off` + never. Platforms declare what they can do through four new peer-stream + driver calls, `wifi_direct_set_fast_link_roles` and its siblings; a custom platform that declares nothing is never asked to host or join. - **Native iOS and Android applications get the SDK's built-in storage.** diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index 517f34334..b70af05a3 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index e7c96dc9b..11b44038a 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index 577a742df..68270172c 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index d1a227821..c3fdc10ba 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index 61c76261e..c1c75b489 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 44d637695..786839376 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index 3a17ce030..50b98ba66 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781 +// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a // Do not edit. #nullable enable diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java index a9bdabaa7..6b7557dd3 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/NamespaceLibrary.java @@ -745,7 +745,7 @@ static void uniffiCheckApiChecksums() { if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != ((short) 15986)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } - if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != ((short) 20631)) { + if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != ((short) 62518)) { throw new RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project"); } if (UniffiLib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != ((short) 12337)) { diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java index 3bf3ed695..42c528365 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocol.java @@ -6168,7 +6168,7 @@ public void wifiDirectPeerDisconnected(java.lang.String peerId) throws ProtocolE @Override - public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin) { + public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin, boolean acceptUnrequested) { try { callWithHandle(_uniffiHandle -> { @@ -6176,7 +6176,7 @@ public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin) { UniffiHelpers.uniffiRustCall( (_allocator, _status) -> { UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(_uniffiHandle, - FfiConverterBoolean.INSTANCE.lower(canHost), FfiConverterBoolean.INSTANCE.lower(canJoin), _status); + FfiConverterBoolean.INSTANCE.lower(canHost), FfiConverterBoolean.INSTANCE.lower(canJoin), FfiConverterBoolean.INSTANCE.lower(acceptUnrequested), _status); }); } catch (java.lang.RuntimeException _uniffi_ex) { throw _uniffi_ex; diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java index 8f21e55b0..cae72bcca 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/OfflineProtocolInterface.java @@ -189,7 +189,7 @@ public interface OfflineProtocolInterface { public FastLinkDirective wifiDirectNextFastLinkDirective(); public void wifiDirectPeerConnected(java.lang.String peerId) throws ProtocolException; public void wifiDirectPeerDisconnected(java.lang.String peerId) throws ProtocolException; - public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin); + public void wifiDirectSetFastLinkRoles(boolean canHost, boolean canJoin, boolean acceptUnrequested); public void wifiDirectStatusChanged(boolean isConnected) throws ProtocolException; } diff --git a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java index ac54b9b3a..963c502ee 100644 --- a/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java +++ b/bindings/java/src/main/java/com/offlineprotocol/sdk/UniffiLib.java @@ -2217,11 +2217,11 @@ static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct } // uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles - private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.ADDRESS)); + private static final java.lang.invoke.MethodHandle MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles = findDowncallHandle("uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles", java.lang.foreign.FunctionDescriptor.ofVoid(java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.JAVA_BYTE, java.lang.foreign.ValueLayout.ADDRESS)); - static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(long ptr, byte canHost, byte canJoin, java.lang.foreign.MemorySegment _uniffiOutErr) { + static void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(long ptr, byte canHost, byte canJoin, byte acceptUnrequested, java.lang.foreign.MemorySegment _uniffiOutErr) { try { - MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.invokeExact(ptr, canHost, canJoin, _uniffiOutErr); + MH_uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.invokeExact(ptr, canHost, canJoin, acceptUnrequested, _uniffiOutErr); } catch (Throwable _ex) { throw new AssertionError("invokeExact failed", _ex); } } diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index 56a2f4254..a8e5d03f0 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "7ea1a6e39085fcd2446161bcca4ee2816f2f2b1ab2582fe7a3aa73417dbac781" +UDL_SHA256 = "64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', @@ -577,7 +577,9 @@ 'wifi_direct_peer_disconnected': ((('peer_id', 'string'),), 'void'), 'wifi_direct_set_fast_link_roles': ((('can_host', 'boolean'), - ('can_join', 'boolean')), + ('can_join', 'boolean'), + ('accept_unrequested', + 'boolean')), 'void'), 'wifi_direct_status_changed': ((('is_connected', 'boolean'),), 'void')}, diff --git a/bindings/python/offline_protocol_sdk/offline_protocol.py b/bindings/python/offline_protocol_sdk/offline_protocol.py index b77bdca73..6744d05a4 100644 --- a/bindings/python/offline_protocol_sdk/offline_protocol.py +++ b/bindings/python/offline_protocol_sdk/offline_protocol.py @@ -1037,7 +1037,7 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != 15986: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 20631: + if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 62518: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != 12337: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -3335,6 +3335,7 @@ def _uniffi_check_api_checksums(lib): ctypes.c_uint64, ctypes.c_int8, ctypes.c_int8, + ctypes.c_int8, ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles.restype = None @@ -11575,7 +11576,7 @@ def wifi_direct_peer_connected(self, peer_id: str) -> None: raise NotImplementedError def wifi_direct_peer_disconnected(self, peer_id: str) -> None: raise NotImplementedError - def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool) -> None: + def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool,accept_unrequested: bool) -> None: raise NotImplementedError def wifi_direct_status_changed(self, is_connected: bool) -> None: raise NotImplementedError @@ -14489,15 +14490,18 @@ def wifi_direct_peer_disconnected(self, peer_id: str) -> None: *_uniffi_lowered_args, ) return _uniffi_lift_return(_uniffi_ffi_result) - def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool) -> None: + def wifi_direct_set_fast_link_roles(self, can_host: bool,can_join: bool,accept_unrequested: bool) -> None: _UniffiFfiConverterBoolean.check_lower(can_host) _UniffiFfiConverterBoolean.check_lower(can_join) + + _UniffiFfiConverterBoolean.check_lower(accept_unrequested) _uniffi_lowered_args = ( self._uniffi_clone_handle(), _UniffiFfiConverterBoolean.lower(can_host), _UniffiFfiConverterBoolean.lower(can_join), + _UniffiFfiConverterBoolean.lower(accept_unrequested), ) _uniffi_lift_return = lambda val: None _uniffi_error_converter = None diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt index abd77a78d..0bc44de2c 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/ProtocolEngineHost.kt @@ -334,6 +334,10 @@ class ProtocolEngineHost( manager.stop() } manager.formGroups = WifiDirectGroupFormation.formGroupsAfterEnable(manager.formGroups, autoAccept) + manager.fastLinkMode = FastLinkMode.parse( + config?.let { json -> if (json.has("fastLink") && !json.isNull("fastLink")) json.getString("fastLink") else null }, + manager.fastLinkMode, + ) wireTransportCallbacks(proto) manager.start() onDiagnostic("info", "WiFi Direct transport enabled", emptyMap()) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index eb62a9991..27a041835 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -158,6 +158,13 @@ class WifiDirectManager( */ @Volatile var formGroups: Boolean = false + /** + * `wifiDirect.fastLink` (ADR 0038): whether this application takes part + * in fast links a peer starts ([FastLinkMode]). Set before [start], which + * declares it with the roles. + */ + @Volatile var fastLinkMode: FastLinkMode = FastLinkMode.ANY + // MARK: - Properties private val wifiP2pManager: WifiP2pManager? = @@ -1466,9 +1473,9 @@ class WifiDirectManager( * Android 10 and later, both host and join. */ private fun declareFastLinkRoles(p2p: Boolean) { - val able = p2p && fastLinkSupported + val able = p2p && fastLinkSupported && fastLinkMode != FastLinkMode.OFF try { - protocol.wifiDirectSetFastLinkRoles(able, able) + protocol.wifiDirectSetFastLinkRoles(able, able, fastLinkMode == FastLinkMode.ANY) } catch (e: Exception) { Log.w(TAG, "Could not declare fast-link roles", e) } @@ -1736,7 +1743,7 @@ class WifiDirectManager( hosted?.let { fastLinkEnded(it.linkId, "failed") } joined?.let { fastLinkEnded(it.linkId, "failed") } try { - protocol.wifiDirectSetFastLinkRoles(false, false) + protocol.wifiDirectSetFastLinkRoles(false, false, false) } catch (_: Exception) {} } @@ -2257,3 +2264,28 @@ internal object FastLinkGroupConfig { } } } + +/** + * `wifiDirect.fastLink`: how far this application takes part in fast links + * (ADR 0038). [ANY] hosts for a peer's request and joins an offer it did not + * ask for; [REQUESTED_ONLY] takes part only in links it asked for, and + * answers the peer's initiative `declined`; [OFF] declares no role. + */ +enum class FastLinkMode { + OFF, REQUESTED_ONLY, ANY; + + companion object { + /** + * The mode a config value names, or [current] when it names none: an + * enable that does not mention `fastLink` keeps the setting, as + * `autoAccept` does. An unknown value is [OFF], so a typo never + * widens what the application allowed. + */ + fun parse(value: String?, current: FastLinkMode): FastLinkMode = when (value) { + null -> current + "any" -> ANY + "requestedOnly" -> REQUESTED_ONLY + else -> OFF + } + } +} diff --git a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt index a81f6abc1..9e159f863 100644 --- a/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt +++ b/bindings/react-native/android/src/main/java/uniffi/offline_protocol/offline_protocol.kt @@ -1894,7 +1894,7 @@ internal object UniffiLib { ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected(`ptr`: Long,`peerId`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, ): Unit - external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(`ptr`: Long,`canHost`: Byte,`canJoin`: Byte,uniffi_out_err: UniffiRustCallStatus, + external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(`ptr`: Long,`canHost`: Byte,`canJoin`: Byte,`acceptUnrequested`: Byte,uniffi_out_err: UniffiRustCallStatus, ): Unit external fun uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed(`ptr`: Long,`isConnected`: Byte,uniffi_out_err: UniffiRustCallStatus, ): Unit @@ -2753,7 +2753,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) { if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() and 0xFFFF) != 15986) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } - if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() and 0xFFFF) != 20631) { + if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() and 0xFFFF) != 62518) { throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") } if ((lib.uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() and 0xFFFF) != 12337) { @@ -5096,7 +5096,7 @@ public interface OfflineProtocolInterface { fun `wifiDirectPeerDisconnected`(`peerId`: kotlin.String) - fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean) + fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean, `acceptUnrequested`: kotlin.Boolean) fun `wifiDirectStatusChanged`(`isConnected`: kotlin.Boolean) @@ -7880,7 +7880,7 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface - override fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean) + override fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean, `acceptUnrequested`: kotlin.Boolean) = callWithHandle { uniffiRustCall() { _status -> @@ -7888,7 +7888,8 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface it, FfiConverterBoolean.lower(`canHost`), - FfiConverterBoolean.lower(`canJoin`),_status) + FfiConverterBoolean.lower(`canJoin`), + FfiConverterBoolean.lower(`acceptUnrequested`),_status) } } diff --git a/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkModeTest.kt b/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkModeTest.kt new file mode 100644 index 000000000..d2bc9e9de --- /dev/null +++ b/bindings/react-native/android/src/test/java/com/offlineprotocol/FastLinkModeTest.kt @@ -0,0 +1,25 @@ +package com.offlineprotocol + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** `wifiDirect.fastLink`: a typo never widens what the application allowed. */ +class FastLinkModeTest { + @Test + fun `each named mode parses`() { + assertEquals(FastLinkMode.ANY, FastLinkMode.parse("any", FastLinkMode.OFF)) + assertEquals(FastLinkMode.REQUESTED_ONLY, FastLinkMode.parse("requestedOnly", FastLinkMode.ANY)) + assertEquals(FastLinkMode.OFF, FastLinkMode.parse("off", FastLinkMode.ANY)) + } + + @Test + fun `an enable that names no mode keeps the current one`() { + assertEquals(FastLinkMode.REQUESTED_ONLY, FastLinkMode.parse(null, FastLinkMode.REQUESTED_ONLY)) + } + + @Test + fun `an unknown mode is off`() { + assertEquals(FastLinkMode.OFF, FastLinkMode.parse("Any", FastLinkMode.ANY)) + assertEquals(FastLinkMode.OFF, FastLinkMode.parse("requested_only", FastLinkMode.ANY)) + } +} diff --git a/bindings/react-native/ios/Generated/offline_protocol.swift b/bindings/react-native/ios/Generated/offline_protocol.swift index e661149be..4fbf44088 100644 --- a/bindings/react-native/ios/Generated/offline_protocol.swift +++ b/bindings/react-native/ios/Generated/offline_protocol.swift @@ -1899,7 +1899,7 @@ public protocol OfflineProtocolProtocol: AnyObject, Sendable { func wifiDirectPeerDisconnected(peerId: String) throws - func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool) + func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool, acceptUnrequested: Bool) func wifiDirectStatusChanged(isConnected: Bool) throws @@ -3776,12 +3776,13 @@ open func wifiDirectPeerDisconnected(peerId: String)throws {try rustCallWithEr } } -open func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool) {try! rustCall() { +open func wifiDirectSetFastLinkRoles(canHost: Bool, canJoin: Bool, acceptUnrequested: Bool) {try! rustCall() { uniffiCallStatus in uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles( self.uniffiCloneHandle(), FfiConverterBool.lower(canHost), - FfiConverterBool.lower(canJoin),uniffiCallStatus + FfiConverterBool.lower(canJoin), + FfiConverterBool.lower(acceptUnrequested),uniffiCallStatus ) } } @@ -12085,7 +12086,7 @@ private let initializationResult: InitializationResult = { if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_peer_disconnected() != 15986) { return InitializationResult.apiChecksumMismatch } - if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 20631) { + if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_set_fast_link_roles() != 62518) { return InitializationResult.apiChecksumMismatch } if (uniffi_offline_protocol_uniffi_checksum_method_offlineprotocol_wifi_direct_status_changed() != 12337) { diff --git a/bindings/react-native/ios/Generated/offline_protocolFFI.h b/bindings/react-native/ios/Generated/offline_protocolFFI.h index 750727149..498f95840 100644 --- a/bindings/react-native/ios/Generated/offline_protocolFFI.h +++ b/bindings/react-native/ios/Generated/offline_protocolFFI.h @@ -1625,7 +1625,7 @@ void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_d #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES #define UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_SET_FAST_LINK_ROLES -void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(uint64_t ptr, int8_t can_host, int8_t can_join, RustCallStatus *_Nonnull out_status +void uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles(uint64_t ptr, int8_t can_host, int8_t can_join, int8_t accept_unrequested, RustCallStatus *_Nonnull out_status ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_OFFLINE_PROTOCOL_UNIFFI_FN_METHOD_OFFLINEPROTOCOL_WIFI_DIRECT_STATUS_CHANGED diff --git a/bindings/react-native/ios/ProtocolEngineHost.swift b/bindings/react-native/ios/ProtocolEngineHost.swift index fae8a1c41..3710e5709 100644 --- a/bindings/react-native/ios/ProtocolEngineHost.swift +++ b/bindings/react-native/ios/ProtocolEngineHost.swift @@ -382,6 +382,7 @@ final class ProtocolEngineHost: TransportManagerDelegate { if manager.state == .running { manager.stop() } + manager.fastLinkMode = FastLinkMode.parse(config?["fastLink"], current: manager.fastLinkMode) wireTransportCallbacks(proto) try manager.start() onDiagnostic("info", "WiFi Direct transport enabled", [:]) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 35190b050..6f6e51b16 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -171,6 +171,9 @@ public class WifiDirectManager: NSObject, TransportManager { private var generation = 0 /// The fast link this device is joining or has joined, if any. private var fastLink: FastLinkJoin? + /// `wifiDirect.fastLink` (ADR 0038). Set before `start()`, which + /// declares it with the roles. + var fastLinkMode: FastLinkMode = .any /// Guards [_state] and [_isPaused], which the lifecycle writes from the /// bridge queue and the send path reads from any thread. Everything @@ -291,8 +294,13 @@ public class WifiDirectManager: NSObject, TransportManager { updateState(.running) try? protocolInstance.wifiDirectStatusChanged(isConnected: true) emitDiagnostic("info", "Peer-stream transport started") - // An iPhone joins a fast link and cannot host one (ADR 0038). - try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: true) + // An iPhone joins a fast link and cannot host one (ADR 0038), as far + // as the application's `wifiDirect.fastLink` allows. + try? protocolInstance.wifiDirectSetFastLinkRoles( + canHost: false, + canJoin: fastLinkMode != .off, + acceptUnrequested: fastLinkMode == .any + ) } public func stop() { @@ -328,7 +336,7 @@ public class WifiDirectManager: NSObject, TransportManager { } try? protocolInstance.wifiDirectStatusChanged(isConnected: false) - try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false) + try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false, acceptUnrequested: false) onLinkQueueSync { endFastLink(reason: "failed") } updateState(.stopped) @@ -1014,3 +1022,23 @@ extension WifiDirectManager { } } } + +/// `wifiDirect.fastLink`: how far this application takes part in fast links +/// (ADR 0038). `.any` joins an offer it did not ask for; `.requestedOnly` +/// takes part only in links it asked for and answers the peer's initiative +/// `declined`; `.off` declares no role. +public enum FastLinkMode: Equatable { + case off, requestedOnly, any + + /// The mode a config value names, or `current` when it names none: an + /// enable that does not mention `fastLink` keeps the setting. An unknown + /// value is `.off`, so a typo never widens what the application allowed. + static func parse(_ value: Any?, current: FastLinkMode) -> FastLinkMode { + guard let value = value else { return current } + switch value as? String { + case "any": return .any + case "requestedOnly": return .requestedOnly + default: return .off + } + } +} diff --git a/bindings/react-native/src/types.ts b/bindings/react-native/src/types.ts index 7fe5e8102..73b5a1d11 100644 --- a/bindings/react-native/src/types.ts +++ b/bindings/react-native/src/types.ts @@ -442,6 +442,20 @@ export interface WifiDirectTransportConfig { * formed in the system's Wi-Fi Direct settings is used. */ autoAccept?: boolean; + /** + * How far this app takes part in fast links (ADR 0038), the Wi-Fi network + * two devices bring up for each other over their session: + * - `'any'` (default): host for a peer's request (Android) and join an + * offer this app did not ask for, which shows the iOS join prompt + * unprompted and moves an Android device onto the peer's group silently. + * - `'requestedOnly'`: take part only in links this app asked for with + * `requestFastLink`; a peer's request or unasked-for offer is answered + * `declined`. Two apps both set to this never link. + * - `'off'`: never host or join one. + * An enable that leaves it out keeps the current setting; an unknown value + * is `'off'`. + */ + fastLink?: 'off' | 'requestedOnly' | 'any'; /** * @deprecated Not used. The device with the lowest address owns a group * the SDK forms. diff --git a/bindings/ruby/lib/offline_protocol.rb b/bindings/ruby/lib/offline_protocol.rb index 19407bc05..b726f32bc 100644 --- a/bindings/ruby/lib/offline_protocol.rb +++ b/bindings/ruby/lib/offline_protocol.rb @@ -7777,7 +7777,7 @@ class VTableCallbackInterfaceWifiDirectTransportCallback < FFI::Struct :void attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles, - [:uint64, :int8, :int8, RustCallStatus.by_ref], + [:uint64, :int8, :int8, :int8, RustCallStatus.by_ref], :void attach_function :uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_status_changed, @@ -13264,12 +13264,14 @@ def wifi_direct_peer_disconnected(peer_id) ::OfflineProtocol.rust_call_with_error(ProtocolError,:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_peer_disconnected,uniffi_clone_handle(),RustBuffer.alloc_from_string(peer_id)) end - def wifi_direct_set_fast_link_roles(can_host, can_join) + def wifi_direct_set_fast_link_roles(can_host, can_join, accept_unrequested) can_host = can_host ? true : false can_join = can_join ? true : false - ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles,uniffi_clone_handle(),(can_host ? 1 : 0),(can_join ? 1 : 0)) + accept_unrequested = accept_unrequested ? true : false + + ::OfflineProtocol.rust_call(:uniffi_offline_protocol_uniffi_fn_method_offlineprotocol_wifi_direct_set_fast_link_roles,uniffi_clone_handle(),(can_host ? 1 : 0),(can_join ? 1 : 0),(accept_unrequested ? 1 : 0)) end def wifi_direct_status_changed(is_connected) diff --git a/crates/offline-protocol-uniffi/src/capi/generated.rs b/crates/offline-protocol-uniffi/src/capi/generated.rs index bca3f107e..82cab120a 100644 --- a/crates/offline-protocol-uniffi/src/capi/generated.rs +++ b/crates/offline-protocol-uniffi/src/capi/generated.rs @@ -2739,8 +2739,9 @@ pub fn call_engine(target: &crate::OfflineProtocol, method: &str, mut args: Fiel "wifi_direct_set_fast_link_roles" => { let arg_can_host = args.take("can_host")?; let arg_can_join = args.take("can_join")?; + let arg_accept_unrequested = args.take("accept_unrequested")?; args.finish()?; - target.wifi_direct_set_fast_link_roles(arg_can_host, arg_can_join); + target.wifi_direct_set_fast_link_roles(arg_can_host, arg_can_join, arg_accept_unrequested); Ok(Value::Null) } "wifi_direct_next_fast_link_directive" => { diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index b1b3c4223..5c1023e4a 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -7988,9 +7988,14 @@ impl OfflineProtocol { } /// The platform says what it can do for a fast link. - pub fn wifi_direct_set_fast_link_roles(&self, can_host: bool, can_join: bool) { + pub fn wifi_direct_set_fast_link_roles( + &self, + can_host: bool, + can_join: bool, + accept_unrequested: bool, + ) { if let Ok(mut guard) = self.lock_inner() { - guard.set_fast_link_roles(can_host, can_join); + guard.set_fast_link_roles(can_host, can_join, accept_unrequested); } } diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index 0cdeee544..785e61cce 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1488,9 +1488,13 @@ interface OfflineProtocol { // docs/state-machines/fast-link.md). The platform declares what it can // do once it knows its permissions: an Android device that can create a // Wi-Fi Direct group with given credentials hosts and joins, an iPhone - // with the Hotspot Configuration entitlement joins. Until it does, both - // are false and every request is refused. - void wifi_direct_set_fast_link_roles(boolean can_host, boolean can_join); + // with the Hotspot Configuration entitlement joins. `accept_unrequested` + // is the application's `wifiDirect.fastLink` setting: true ("any") takes + // part in links a peer starts, false ("requestedOnly") answers a peer's + // request or unasked-for offer `declined`, so no join prompt or group ever + // appears that this application did not ask for. Until the platform + // declares, all are false and every request is refused. + void wifi_direct_set_fast_link_roles(boolean can_host, boolean can_join, boolean accept_unrequested); // The next instruction for the platform, drained alongside // `wifi_direct_get_next_message` whenever the transport callback fires: diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 162c9fcee..3c0be05b5 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -89,13 +89,20 @@ pub const MAX_ENDED_REMEMBERED: usize = 16; /// 250 bytes. pub const MAX_FRAME_BODY_BYTES: usize = 2048; -/// What this device's platform can do. Both false until it says otherwise. +/// What this device's platform can do, and what its application allows. +/// All false until the platform says otherwise. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct FastLinkRoles { /// It can bring up a network for a peer and admit only that peer. pub can_host: bool, /// It can join a network by name and passphrase and dial an address on it. pub can_join: bool, + /// The application takes part in links a peer starts: it hosts for a + /// peer's request and joins an offer it did not ask for. Without it only + /// links this device's application asked for go ahead, and the peer's + /// initiative is answered `declined`, so no join prompt and no group ever + /// appears that this application did not ask for. + pub accept_unrequested: bool, } /// Which side of a link this device is. @@ -752,6 +759,10 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::CannotHost); return; } + if !self.roles.accept_unrequested { + self.reply_close(peer, link_id, CloseReason::Declined); + return; + } self.host_backoff .retain(|(_, at)| now.saturating_duration_since(*at) < HOST_BACKOFF); if self @@ -789,11 +800,15 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::Declined); return; } + // Whether this device's application asked for a link with the peer: + // its request is waiting, or it is hosting for the peer itself. + let mut asked = false; if let Some(link) = self.link.clone() { if link.peer != peer { self.reply_close(peer, link_id, CloseReason::Busy); return; } + asked = true; match link.role { FastLinkRole::Host => { // Both are hosting for each other. The lower address @@ -834,6 +849,10 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::CannotJoin); return; } + if !asked && !self.roles.accept_unrequested { + self.reply_close(peer, link_id, CloseReason::Declined); + return; + } let ttl = Duration::from_millis(offer.ttl_ms.min(MAX_OFFER_TTL_MS)); self.directives.push_back(PendingDirective { directive: FastLinkDirective { @@ -1189,6 +1208,7 @@ mod tests { FastLinkRoles { can_host: true, can_join: true, + accept_unrequested: true, } } @@ -1196,6 +1216,7 @@ mod tests { FastLinkRoles { can_host: false, can_join: true, + accept_unrequested: true, } } @@ -2205,6 +2226,71 @@ mod tests { ); } + #[test] + fn a_device_that_takes_only_its_own_links_declines_the_peers_initiative() { + let t0 = Instant::now(); + let own_only = |roles: FastLinkRoles| FastLinkRoles { + accept_unrequested: false, + ..roles + }; + let mut android = machine(own_only(host_roles())); + let mut iphone = machine(own_only(join_roles())); + + // A peer's request is declined, not hosted. + let id = fresh(1).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(2), + t0, + 0, + ); + assert!(!android.has_directives()); + assert_eq!( + android.take_frames()[0].1.body, + FrameBody::Close { + reason: "declined".to_string() + } + ); + + // An offer nobody here asked for is declined, never prompted. + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer.clone())), + fresh(3), + t0, + 0, + ); + assert!(!iphone.has_directives()); + iphone.take_frames(); + + // An offer that answers this device's own request goes ahead. + let asked = iphone.request(LOW, fresh(4), t0).unwrap(); + iphone.take_frames(); + iphone.on_frame( + LOW, + HIGH, + Frame::new(&asked, FrameBody::Offer(offer)), + fresh(5), + t0, + 0, + ); + assert_eq!( + iphone.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Join + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 1e977b91d..633f591c5 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -25,11 +25,20 @@ use crate::fast_link::{ use crate::{Error, Event, Result}; impl OfflineProtocol { - /// Declares what this device's platform can do. Until it does, both are + /// Declares what this device's platform can do, and whether its + /// application takes part in links a peer starts. Until it does, all are /// false and every request is refused or answered `cannot_*`. - pub fn set_fast_link_roles(&mut self, can_host: bool, can_join: bool) { - self.fast_links - .set_roles(FastLinkRoles { can_host, can_join }); + pub fn set_fast_link_roles( + &mut self, + can_host: bool, + can_join: bool, + accept_unrequested: bool, + ) { + self.fast_links.set_roles(FastLinkRoles { + can_host, + can_join, + accept_unrequested, + }); } /// Asks for a fast link to `peer`, and returns its id. diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index dc8f134f9..d6413f2b1 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -113,8 +113,8 @@ fn pair() -> (Node, Node) { node.protocol.peer_fast_link.insert(peer.clone()); node.transport.add_connected_peer(peer, -40); } - alice.protocol.set_fast_link_roles(true, true); - bob.protocol.set_fast_link_roles(false, true); + alice.protocol.set_fast_link_roles(true, true, true); + bob.protocol.set_fast_link_roles(false, true, true); (alice, bob) } @@ -240,14 +240,14 @@ fn a_request_is_refused_without_capability_session_or_roles() { .confirmed_sessions .insert(bob.address.clone()); - alice.protocol.set_fast_link_roles(false, false); + alice.protocol.set_fast_link_roles(false, false, false); assert!(matches!( alice.protocol.request_fast_link(&bob.address), Err(Error::InvalidState(_)) )); alice.transport.remove_connected_peer(&bob.address); - alice.protocol.set_fast_link_roles(true, true); + alice.protocol.set_fast_link_roles(true, true, true); assert!( alice.protocol.request_fast_link(&bob.address).is_err(), "a request needs a live direct link to carry it" @@ -259,7 +259,7 @@ fn a_request_is_refused_without_capability_session_or_roles() { #[test] fn a_peer_that_cannot_host_says_so() { let (mut alice, mut bob) = pair(); - alice.protocol.set_fast_link_roles(false, true); + alice.protocol.set_fast_link_roles(false, true, true); bob.protocol.request_fast_link(&alice.address).unwrap(); alice.deliver(bob.take_sent()); diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 32a3c506d..e73857f30 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -58,7 +58,11 @@ the foreground and deleted the passphrase. Android 10 and later both, iOS join only, everything else neither. A requester that can host hosts; one that can only join asks its peer to host. When both ask at once, the lower address (compared by UTF-8 bytes, as - for streams) hosts and the other side joins. + for streams) hosts and the other side joins. Whether a device takes part in + a link its peer starts is its application's choice too, through + `wifiDirect.fastLink`: `any` (the default) hosts for a peer's request and + joins an offer it did not ask for, `requestedOnly` answers both `declined`, + `off` declares no role. 4. **The engine makes the credentials, fresh for every link.** The network name is `DIRECT-`, two random characters, `-` and twelve random hex digits: diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index 771db05c3..ace576c11 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -140,7 +140,10 @@ the local-network keys above, since the stream is a local-network connection. Without the entitlement every join ends `failed`. iOS shows "“App” Wants to Join Wi‑Fi Network “DIRECT-…”?" on every join, and -the phone leaves its own Wi-Fi while the link lasts. Ask for a link when a +the phone leaves its own Wi-Fi while the link lasts. By default a peer's app +can start a link too, which shows that prompt without your app asking; set +`wifiDirect.fastLink` to `'requestedOnly'` to take part only in links your +app requests, or `'off'` to never join one. Ask for a link when a transfer is worth that to your user. The link ends when the app leaves the foreground. diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 801763f08..d82866211 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1483,7 +1483,9 @@ own Wi-Fi, dials the group owner's address and not the offer's), and the stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most 300 s later. It can also put the iOS join prompt in front of a user who did -not ask: an offer needs no request. Once the user declines, that peer's +not ask: an offer needs no request, unless the application set +`wifiDirect.fastLink` to `requestedOnly`, which answers every offer it did not +ask for `declined` and never shows it. Under the default, once the user declines, that peer's offers are refused for ten minutes, and a second offer while one is on screen is refused, so the most it gets is one prompt per ten minutes per session. An Android joiner shows no prompt at all: Wi-Fi Direct joins a group by name and diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index c7cfacd44..4fd17a65c 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -49,8 +49,12 @@ wake-up that drains outbound stream bodies: | `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | A platform declares what it can do with -`wifi_direct_set_fast_link_roles(can_host, can_join)`. Until it does, both are -false and every request is refused. +`wifi_direct_set_fast_link_roles(can_host, can_join, accept_unrequested)`. +Until it does, all are false and every request is refused. The third is the +application's `wifiDirect.fastLink` setting, not the platform's: with it +false (`requestedOnly`), a peer's `request` and an `offer` this device did +not ask for are answered `declined`, so only links this application asked +for go ahead and no join prompt or group appears that it did not want. ## The host From aa1b4f0fd650e1a9c8f4aca34154f347afc86b99 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:13:55 +0530 Subject: [PATCH 37/81] fix(protocol): a peer's decline never pauses that peer's own offers --- crates/offline-protocol/src/fast_link.rs | 34 +++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 3c0be05b5..5e2be0da6 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -1105,7 +1105,12 @@ impl FastLinks { } self.ended_joins .push_back((link.id.clone(), link.peer.clone())); - if reason == CloseReason::Declined { + // Only this device's user declining a network it was asked to + // join starts the pause. A peer's `declined` answers this + // device's request; counting it refused that peer's own link + // for ten minutes, with no prompt ever shown here. + if reason == CloseReason::Declined && tell_peer && link.state == FastLinkState::Joining + { self.record_decline(link.peer.clone(), now); } } @@ -2291,6 +2296,33 @@ mod tests { ); } + #[test] + fn a_peers_decline_never_pauses_its_own_offers() { + let t0 = Instant::now(); + let mut android = machine(FastLinkRoles { + accept_unrequested: false, + ..host_roles() + }); + let mut iphone = machine(join_roles()); + + // The iPhone asks; the Android takes only its own links. + iphone.request(LOW, fresh(1), t0).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, t0, 0); + deliver(&mut android, LOW, &mut iphone, HIGH, t0, 0); + assert!(iphone.peer().is_none(), "the request ended with declined"); + + // The Android's user then asks; the iPhone's user saw no prompt, so + // the offer goes ahead. + let id = android.request(HIGH, fresh(2), t0).unwrap(); + android.next_directive(t0); + assert!(android.hosting(&id, "192.168.49.1", 8988, t0, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, t0, 0); + assert_eq!( + iphone.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Join + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); From 22b56bb8669e977fd4d203f65f90140c1f1d3c62 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:17:23 +0530 Subject: [PATCH 38/81] fix(protocol): a transfer on a fast link fails as soon as the link ends --- bindings/react-native/src/index.ts | 3 +- crates/offline-protocol/src/fast_link.rs | 12 +++ .../src/protocol/fast_link.rs | 30 ++++++++ .../src/protocol/tests/fast_link.rs | 74 +++++++++++++++++++ ...fast-link-is-offered-inside-the-session.md | 7 +- docs/state-machines/fast-link.md | 7 ++ 6 files changed, 130 insertions(+), 3 deletions(-) diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index 81d2f4792..e7a251fdf 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4610,7 +4610,8 @@ export class OfflineProtocol { * transport selection: a 1 MiB file that takes minutes over Bluetooth takes * seconds over it. A file transfer keeps the carrier it started on, so send * after the `fast_link_changed` event with state `up` for it to use the - * link. + * link. A transfer on the link when it ends fails at once with + * `media_send_failed`; send it again and it goes over what remains. * * Resolves with the link id as soon as the first step is taken; the outcome * arrives as `fast_link_changed` events. On iOS the join shows a system diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 5e2be0da6..eeff02ec8 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -547,6 +547,10 @@ pub(crate) struct FastLinks { unanswered: VecDeque<(String, u8)>, /// Peers whose requests are refused, and since when ([`HOST_BACKOFF`]). host_backoff: VecDeque<(String, Instant)>, + /// Peers whose link ended after it was up. A transfer pinned to the + /// slot for one of them can no longer reach it: its carrier is fixed when + /// it starts, so it would retry on a dead slot until its retries ran out. + released: VecDeque, } impl FastLinks { @@ -1090,6 +1094,9 @@ impl FastLinks { self.directives .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); + if link.state == FastLinkState::Up { + self.released.push_back(link.peer.clone()); + } if link.role == FastLinkRole::Host && link.requested_by_peer { self.count_hosting( &link.peer, @@ -1190,6 +1197,11 @@ impl FastLinks { pub(crate) fn take_changes(&mut self) -> Vec { self.changes.drain(..).collect() } + + /// Peers whose link ended after it was up, since the last call. + pub(crate) fn take_released(&mut self) -> Vec { + self.released.drain(..).collect() + } } #[cfg(test)] diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 633f591c5..a02057418 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -215,6 +215,33 @@ impl OfflineProtocol { transfer.pinned_transport == TransportType::WiFiDirect } + /// A link to `peer` that was up has ended: each transfer to it pinned to + /// the slot fails now, with its chunks withdrawn. Its carrier is fixed + /// when it starts, so it would otherwise retry on a slot that no longer + /// reaches the peer until its retries ran out, and its chunks are sized + /// for the stream, larger than Bluetooth carries. The application hears + /// `media_send_failed` and can send again over what remains. + fn fail_transfers_on_ended_link(&mut self, peer: &str) { + let files: Vec = self + .outbound_media_transfers + .iter() + .filter(|(_, transfer)| transfer.recipient == peer && Self::holds_fast_link(transfer)) + .map(|(file_id, _)| file_id.clone()) + .collect(); + for file_id in files { + let chunks: Vec<_> = self + .outbound_media_chunks + .iter() + .filter(|(_, (chunk_file, _))| *chunk_file == file_id) + .map(|(message_id, _)| message_id.clone()) + .collect(); + for message_id in &chunks { + self.forget_outbound_message(message_id); + } + self.abort_outbound_media_transfer(&file_id, "the fast link carrying it closed"); + } + } + /// Whether a peer stream holds `peer` now. fn peer_stream_proves(&self, peer: &str) -> bool { self.transport_manager @@ -241,6 +268,9 @@ impl OfflineProtocol { for change in self.fast_links.take_changes() { self.emit_event(Event::fast_link_changed(change)); } + for peer in self.fast_links.take_released() { + self.fail_transfers_on_ended_link(&peer); + } if self.fast_links.has_directives() { self.wake_peer_stream_platform(); } diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index d6413f2b1..30baaef49 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -416,6 +416,80 @@ fn only_a_transfer_on_the_peer_stream_holds_the_link() { assert!(OfflineProtocol::holds_fast_link(&on_stream)); } +/// A link that was up ends: a transfer pinned to the slot fails at once with +/// its chunks withdrawn, rather than retrying on a slot that no longer +/// reaches the peer until its retries run out. One on Bluetooth carries on. +#[test] +fn a_transfer_on_the_link_fails_when_the_link_ends() { + use offline_protocol_core::ContentType; + + let (mut alice, mut bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + bob.deliver(alice.take_sent()); + alice.protocol.fast_link_stream_proved(&bob.address); + + let mut send = |name: &str| { + alice + .protocol + .send_media( + &bob.address, + vec![0x5a; 64 * 1024], + name, + ContentType::File, + None, + ) + .unwrap() + }; + let on_link = send("fast.bin"); + let on_bluetooth = send("slow.bin"); + // The mock has no stream, so pin the first the way a proved one would. + alice + .protocol + .outbound_media_transfers + .get_mut(&on_link) + .unwrap() + .pinned_transport = TransportType::WiFiDirect; + let link_chunks: Vec<_> = alice + .protocol + .outbound_media_chunks + .iter() + .filter(|(_, (file, _))| *file == on_link) + .map(|(message, _)| message.clone()) + .collect(); + assert!(!link_chunks.is_empty()); + + alice.protocol.fast_link_stream_lost(&bob.address); + + assert!(!alice + .protocol + .outbound_media_transfers + .contains_key(&on_link)); + assert!(alice + .protocol + .outbound_media_transfers + .contains_key(&on_bluetooth)); + for message in &link_chunks { + assert!(!alice.protocol.media_outbox.contains_key(message)); + assert!(!alice.protocol.outbound_media_chunks.contains_key(message)); + } + let failed: Vec = alice + .events + .lock() + .unwrap() + .iter() + .filter_map(|event| match event { + Event::MediaSendFailed { file_id, .. } => Some(file_id.clone()), + _ => None, + }) + .collect(); + assert_eq!(failed, [on_link]); +} + /// Pausing the engine ends a link: a paused engine runs no timers, so an /// Android host's group would otherwise stay up until the app returned. #[test] diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index e73857f30..0b36beb66 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -15,8 +15,11 @@ The engine already has a slot for a faster link, the peer stream the peer's address, everything above the slot works: the transport selector weights the slot by bandwidth, a file transfer pins to it once a stream proves the recipient, and outboxes and acknowledgements make falling back to -Bluetooth lossless. What two phones without a shared network lack is a network -to open the stream over. +Bluetooth lossless for messages. A file transfer keeps the carrier it started +on, so one in flight when a link ends fails at once +([ending a link](../state-machines/fast-link.md#ending-a-link)) and the +application sends it again. What two phones without a shared network lack is +a network to open the stream over. Neither platform lets an application make one silently, but each lets it make one with credentials: diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 4fd17a65c..0feeb1f68 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -143,6 +143,13 @@ presence update every 15 s held a link up indefinitely when they did. A link that carries nothing large for 60 s is costing the user their own Wi-Fi for no reason. +A link that was up and ends fails every file transfer to the peer that was +pinned to the slot, at once, with `media_send_failed`, and withdraws its +chunks. A transfer's carrier is fixed when it starts, so it would otherwise +retry on a slot that no longer reaches the peer until its retries ran out, +and its chunks are sized for the stream, larger than Bluetooth carries. The +application sends it again over what remains. + Pausing the engine ends a link with `background`: a paused engine runs none of these timers, and a host's group would otherwise stay on the air until the application returned, with nothing bounding it. From 0850fb17e215649b3d1ba2af3839c761555b381b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:19:15 +0530 Subject: [PATCH 39/81] fix(protocol): stopping the engine ends a fast link --- .../src/protocol/fast_link.rs | 9 +++--- crates/offline-protocol/src/protocol/mod.rs | 7 ++++- .../src/protocol/tests/fast_link.rs | 30 +++++++++++++++++++ docs/state-machines/fast-link.md | 4 ++- 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index a02057418..11830d46a 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -92,12 +92,11 @@ impl OfflineProtocol { closed } - /// The engine is pausing: any link ends with `background`, the peer and - /// this device's platform told. - pub(crate) fn end_fast_link_on_pause(&mut self) { + /// The engine is pausing (`background`) or stopping (`closed`): any link + /// ends, the peer and this device's platform told. + pub(crate) fn end_fast_link_for(&mut self, reason: CloseReason) { if let Some(peer) = self.fast_links.peer().map(str::to_string) { - self.fast_links - .end_for(&peer, CloseReason::Background, Instant::now()); + self.fast_links.end_for(&peer, reason, Instant::now()); self.flush_fast_link(); } } diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index c41c88793..abaee4cc6 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -2402,6 +2402,11 @@ impl OfflineProtocol { // take the cancellations. Nothing pumps relays or sweeps deadlines once // stopped, so a resolution left here is an event that never comes. self.flush_username_resolutions_for_stop(); + // A stopped engine runs no timers either, and a platform that starts + // it again would find a link from before still held, answering every + // request `busy`. It ends while the transport can still carry the + // peer's `close`. + self.end_fast_link_for(crate::fast_link::CloseReason::Closed); // Clear event callbacks to release shared_state references. // NOTE: the routing-decision callback is deliberately NOT cleared @@ -2439,7 +2444,7 @@ impl OfflineProtocol { // A paused engine runs no timers, so a fast link would outlive every // bound its state machine promises while the host's group stays on // the air. It ends here, as the iPhone's side already does. - self.end_fast_link_on_pause(); + self.end_fast_link_for(crate::fast_link::CloseReason::Background); Ok(()) } diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 30baaef49..b93e1b786 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -490,6 +490,36 @@ fn a_transfer_on_the_link_fails_when_the_link_ends() { assert_eq!(failed, [on_link]); } +/// Stopping the engine ends a link too: a platform that starts it again +/// would otherwise find the old link held and every request answered `busy`. +#[test] +fn stopping_the_engine_ends_a_link() { + let (mut alice, mut bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + bob.deliver(alice.take_sent()); + + alice.protocol.stop().unwrap(); + assert_eq!( + alice.protocol.next_fast_link_directive().unwrap().kind, + FastLinkDirectiveKind::Close + ); + assert_eq!( + alice.link_states().last().unwrap(), + &("closed".to_string(), Some("closed".to_string())) + ); + bob.protocol.next_fast_link_directive(); + bob.deliver(alice.take_sent()); + assert_eq!( + bob.link_states().last().unwrap(), + &("closed".to_string(), Some("closed".to_string())) + ); +} + /// Pausing the engine ends a link: a paused engine runs no timers, so an /// Android host's group would otherwise stay up until the app returned. #[test] diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 0feeb1f68..87b2115c2 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -152,7 +152,9 @@ application sends it again over what remains. Pausing the engine ends a link with `background`: a paused engine runs none of these timers, and a host's group would otherwise stay on the air until the -application returned, with nothing bounding it. +application returned, with nothing bounding it. Stopping it ends a link with +`closed`, for the same reason and one more: an engine started again would +find the old link still held and answer every request `busy`. A joiner's platform that is about to lose the network reports it as `ended` first: on iOS, leaving the foreground, after which iOS disconnects at 15 s From 5cc582b9495afc035fdff7497fc984700e60ddc9 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:21:17 +0530 Subject: [PATCH 40/81] fix(bindings): read a hotspot error's code only in its own domain --- .../react-native/ios/WifiDirectManager.swift | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 6f6e51b16..83adda18e 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -14,6 +14,8 @@ import Network // every use of Network's ambiguous in this file. import class NetworkExtension.NEHotspotConfiguration import class NetworkExtension.NEHotspotConfigurationManager +import enum NetworkExtension.NEHotspotConfigurationError +import let NetworkExtension.NEHotspotConfigurationErrorDomain /// The engine's peer-stream slot on iOS, over `NWListener`, `NWBrowser` and /// `NWConnection`. @@ -891,10 +893,18 @@ private final class FastLinkJoin { extension WifiDirectManager { /// Gives a dial this long to become ready before it is tried again. private static let FAST_LINK_REDIAL: TimeInterval = 2.0 - /// `NEHotspotConfigurationError.userDenied`. - private static let HOTSPOT_USER_DENIED = 7 - /// `NEHotspotConfigurationError.alreadyAssociated`: the join holds. - private static let HOTSPOT_ALREADY_ASSOCIATED = 13 + + /// Whether `error` is the hotspot error `code`. The domain is checked: + /// another framework's error that shares the number would otherwise read + /// as the user's refusal, starting the peer's decline pause, or as a join + /// that held. + private static func isHotspotError( + _ error: NSError?, _ code: NEHotspotConfigurationError + ) -> Bool { + guard let error = error else { return false } + return error.domain == NEHotspotConfigurationErrorDomain + && error.code == code.rawValue + } /// Runs what the engine asked for. linkQueue only. fileprivate func drainFastLinkDirectives() { @@ -950,13 +960,13 @@ extension WifiDirectManager { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: link.ssid) // A refusal still counts against the peer, which may have closed // its link on purpose to keep the user's Cancel from registering. - if error?.code == Self.HOTSPOT_USER_DENIED { + if Self.isHotspotError(error, .userDenied) { protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "declined") } return } - if let error = error, error.code != Self.HOTSPOT_ALREADY_ASSOCIATED { - let reason = error.code == Self.HOTSPOT_USER_DENIED ? "declined" : "failed" + if let error = error, !Self.isHotspotError(error, .alreadyAssociated) { + let reason = Self.isHotspotError(error, .userDenied) ? "declined" : "failed" emitDiagnostic("warning", "Fast link: the join did not happen", context: [ "linkId": link.linkId, "reason": reason, From bcb040c0124f42132b379bc90d9cf1bacd140e53 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:32:07 +0530 Subject: [PATCH 41/81] fix(protocol): a fast-link frame that waited for the session is never acted on --- .../src/protocol/message_dispatch.rs | 9 ++- crates/offline-protocol/src/protocol/mod.rs | 10 ++++ .../src/protocol/pending_queue.rs | 7 ++- .../src/protocol/tests/fast_link.rs | 56 +++++++++++++++++++ docs/state-machines/fast-link.md | 3 + 5 files changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/protocol/message_dispatch.rs b/crates/offline-protocol/src/protocol/message_dispatch.rs index a1dae4348..3c698d849 100644 --- a/crates/offline-protocol/src/protocol/message_dispatch.rs +++ b/crates/offline-protocol/src/protocol/message_dispatch.rs @@ -1679,7 +1679,14 @@ impl OfflineProtocol { self.handle_sealed_service_frame(&sender_owned, &frame, message); } if let Some(frame) = fast_link_frame { - self.handle_fast_link_frame(&sender_owned, &frame); + if self.draining_pending_decryption { + debug!( + sender = %sender_owned, + "Dropping a fast-link frame that waited for the session" + ); + } else { + self.handle_fast_link_frame(&sender_owned, &frame); + } } surfaced } diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index abaee4cc6..b72841575 100644 --- a/crates/offline-protocol/src/protocol/mod.rs +++ b/crates/offline-protocol/src/protocol/mod.rs @@ -456,6 +456,15 @@ pub struct OfflineProtocol { /// process. pub(crate) fast_links: crate::fast_link::FastLinks, + /// Set while the pending-decryption queue is drained. A fast-link frame + /// decrypted then is consumed and never acted on: it is only ever acted + /// on from a live decrypt (invariant 1 of + /// `docs/state-machines/fast-link.md`). The queue keeps entries for a + /// day, so a drained request would bring up a group for a requester that + /// gave up long ago, and a drained offer would prompt for a network + /// already gone. + pub(crate) draining_pending_decryption: bool, + /// Delivery ACKs waiting to be coalesced, per peer: the carrier the /// answered frames arrived on, when the first was held, and the answered /// ids with the first one's hop count. Sent as one frame once @@ -1339,6 +1348,7 @@ impl OfflineProtocol { peer_coalesced_ack: std::collections::HashSet::new(), peer_fast_link: std::collections::HashSet::new(), fast_links: crate::fast_link::FastLinks::default(), + draining_pending_decryption: false, coalesced_acks_out: HashMap::new(), answered_deliveries: HashMap::new(), mesh_resend_generations: HashMap::new(), diff --git a/crates/offline-protocol/src/protocol/pending_queue.rs b/crates/offline-protocol/src/protocol/pending_queue.rs index fe3d8a075..8a2c16125 100644 --- a/crates/offline-protocol/src/protocol/pending_queue.rs +++ b/crates/offline-protocol/src/protocol/pending_queue.rs @@ -339,7 +339,12 @@ impl OfflineProtocol { continue; } - if let Some(result) = self.process_internal_message(&msg) { + // A fast-link frame among these is consumed, not acted on: it + // names a moment that has passed (see the field). + self.draining_pending_decryption = true; + let result = self.process_internal_message(&msg); + self.draining_pending_decryption = false; + if let Some(result) = result { match result { InternalMessageResult::Decrypted(content) => { let mut decrypted_msg = msg.clone(); diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index b93e1b786..9e53e30ad 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -490,6 +490,62 @@ fn a_transfer_on_the_link_fails_when_the_link_ends() { assert_eq!(failed, [on_link]); } +/// An offer that reached the joiner before its session did waits in the +/// pending-decryption queue, which keeps entries for a day. When it drains it +/// is consumed, never acted on: it names a network that may be long gone, and +/// acting on it would prompt the user to join nothing. +#[test] +fn a_frame_that_waited_for_the_session_is_never_acted_on() { + let mut alice = Node::new("alice"); + let mut bob = Node::new("bob"); + // Alice holds a session bob has not joined yet. + let welcome = { + let bob_kp = { + let manager = bob.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager.get_or_create_key_package().unwrap() + }; + let manager = alice.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager + .import_key_package(&bob.address, &bob_kp.key_package_data) + .unwrap(); + manager.create_session(&bob.address).unwrap() + }; + for (node, peer) in [(&mut alice, bob.address.clone()), (&mut bob, id("alice"))] { + node.protocol.record_encryption_capable(&peer); + node.protocol.peer_fast_link.insert(peer.clone()); + node.transport.add_connected_peer(peer, -40); + } + alice + .protocol + .persist_session_state(&bob.address, SessionState::Confirmed, "test") + .unwrap(); + alice + .protocol + .confirmed_sessions + .insert(bob.address.clone()); + alice.protocol.set_fast_link_roles(true, true, true); + bob.protocol.set_fast_link_roles(false, true, true); + + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + bob.deliver(alice.take_sent()); + assert!(bob.link_states().is_empty(), "with no session it waits"); + + { + let manager = bob.protocol.mls_manager.as_ref().unwrap().read().unwrap(); + manager.join_session(&welcome).unwrap(); + } + bob.protocol.process_pending_decryption(&id("alice")); + + assert!(bob.protocol.next_fast_link_directive().is_none()); + assert!(bob.link_states().is_empty()); + assert!(bob.protocol.fast_links.peer().is_none()); +} + /// Stopping the engine ends a link too: a platform that starts it again /// would otherwise find the old link held and every request answered `busy`. #[test] diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 87b2115c2..59ad7b419 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -15,6 +15,9 @@ what each shape prevents. over a live direct link (Bluetooth LE whenever the peer is linked there, never down the stream the frame may be ending), and never enters the outbox, a relay or a neighbour's custody. A frame that arrives in plaintext is never routed here. + Nor is one that reached this device before its session did: it waits + undecrypted with every other sealed body, for up to a day, and is consumed + when the session is ready, never acted on. 2. **A link never announces a peer.** Only a stream's preamble does, exactly as on every other network. The joiner's stream is opened with the host's address as its claim, and the host refuses any other proved address on the From 8a334f66ee7fba2414719e2ba5b47621732db4d5 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:34:09 +0530 Subject: [PATCH 42/81] fix(bindings): an iphone dials a fast link only from the offered network --- .../react-native/ios/WifiDirectManager.swift | 40 ++++++++++++++++++- docs/mobile-permissions.md | 4 +- docs/security/threat-model.md | 6 ++- docs/state-machines/fast-link.md | 2 +- 4 files changed, 46 insertions(+), 6 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 83adda18e..007a21f2d 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -14,6 +14,7 @@ import Network // every use of Network's ambiguous in this file. import class NetworkExtension.NEHotspotConfiguration import class NetworkExtension.NEHotspotConfigurationManager +import class NetworkExtension.NEHotspotNetwork import enum NetworkExtension.NEHotspotConfigurationError import let NetworkExtension.NEHotspotConfigurationErrorDomain @@ -297,10 +298,14 @@ public class WifiDirectManager: NSObject, TransportManager { try? protocolInstance.wifiDirectStatusChanged(isConnected: true) emitDiagnostic("info", "Peer-stream transport started") // An iPhone joins a fast link and cannot host one (ADR 0038), as far - // as the application's `wifiDirect.fastLink` allows. + // as the application's `wifiDirect.fastLink` allows. Only from iOS + // 14, which can say what network the phone is on: a join is dialed + // only once it is on the offered one (`dialFastLink`). + let canConfirmNetwork: Bool + if #available(iOS 14.0, *) { canConfirmNetwork = true } else { canConfirmNetwork = false } try? protocolInstance.wifiDirectSetFastLinkRoles( canHost: false, - canJoin: fastLinkMode != .off, + canJoin: fastLinkMode != .off && canConfirmNetwork, acceptUnrequested: fastLinkMode == .any ) } @@ -997,6 +1002,37 @@ extension WifiDirectManager { } guard streams.count < Self.MAX_STREAMS, let port = NWEndpoint.Port(rawValue: link.port) else { return } + // Dialed only from the offered network. `apply` can finish with no + // error while the phone stays on its own Wi-Fi (a wrong passphrase, + // a group already gone), and `.wifi` alone would then send the dial, + // and the preamble, to whatever the offer named on the user's home + // network. Until the phone is on it, the dial waits; the engine's + // deadline bounds the wait. + guard #available(iOS 14.0, *) else { return } + NEHotspotNetwork.fetchCurrent { [weak self] network in + guard let self = self else { return } + self.linkQueue.async { + guard self.fastLink === link else { return } + if network?.ssid == link.ssid { + self.openFastLinkStream(link, port: port) + } else { + self.scheduleFastLinkRedial(link) + } + } + } + } + + /// Opens the link's stream, bound to Wi-Fi, claiming the host. linkQueue + /// only, and only once the phone is on the link's network. + private func openFastLinkStream(_ link: FastLinkJoin, port: NWEndpoint.Port) { + guard link.joined, state == .running, + ProcessInfo.processInfo.systemUptime < link.deadline, + streams.count < Self.MAX_STREAMS else { return } + if let held = peers.handle(for: link.peer), streams.contains(held) { return } + if let current = link.stream as? Stream, streams.contains(current) { + scheduleFastLinkRedial(link) + return + } let parameters = Self.makeParameters() parameters.requiredInterfaceType = .wifi let stream = Stream( diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index ace576c11..ece4fc13e 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -137,7 +137,9 @@ Bluetooth. An iPhone joins the network the peer hosts, which needs the `com.apple.developer.networking.HotspotConfiguration` to the app's entitlements (Xcode adds it to the App ID with automatic signing), and keep the local-network keys above, since the stream is a local-network connection. -Without the entitlement every join ends `failed`. +Without the entitlement every join ends `failed`. An iPhone joins from iOS +14, which can say what network the phone is on; below it a request is refused +and a peer's offer answered `cannot_join`. iOS shows "“App” Wants to Join Wi‑Fi Network “DIRECT-…”?" on every join, and the phone leaves its own Wi-Fi while the link lasts. By default a peer's app diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index d82866211..171d99870 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1478,8 +1478,10 @@ the host's address and can hand them on, and a peer that shares a session can already send anything. A hostile session peer can offer a network it controls and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial -stays on the group (an iPhone binds it to Wi-Fi; an Android, which keeps its -own Wi-Fi, dials the group owner's address and not the offer's), and the +stays on the group (an iPhone dials only once iOS reports it is on the +offered network, since a join can finish with no error while the phone stays +on its own Wi-Fi; an Android, which keeps its own Wi-Fi, dials the group +owner's address and not the offer's), and the stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most 300 s later. It can also put the iOS join prompt in front of a user who did diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 59ad7b419..3588c1049 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -48,7 +48,7 @@ wake-up that drains outbound stream bodies: | Directive | The platform | Then reports | |-----------|--------------|--------------| | `host` | Brings up a network with the given name and passphrase, admitting the given peer only | `wifi_direct_fast_link_hosting(link, host, port)`, or `wifi_direct_fast_link_ended(link, reason)` | -| `join` | Joins the given network and dials `host:port` (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | +| `join` | Joins the given network and, once the system reports it is on it, dials `host:port` (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | | `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | A platform declares what it can do with From 118de5ef8aba01314d4225063b6c58450a938a60 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:34:54 +0530 Subject: [PATCH 43/81] fix(bindings): an android fast link's state clears even with no channel --- .../com/offlineprotocol/WifiDirectManager.kt | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 27a041835..410d9b266 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1630,22 +1630,27 @@ class WifiDirectManager( /** Ends what this device holds for the link: leaves or removes the group. */ @SuppressLint("MissingPermission") private fun closeFastLink(linkId: String) { - val p2p = wifiP2pManager ?: return - val ch = channel ?: return + // The link's fields are cleared even with no manager or channel to + // act through: left set, every later host or join would be refused + // as if this link still held the radio, until the manager restarted. + val p2p = wifiP2pManager + val ch = channel val hosted = fastLinkHosted val joined = fastLinkJoined if (parkedFastLinkJoin?.linkId == linkId) parkedFastLinkJoin = null if (hosted?.linkId == linkId) { fastLinkHosted = null - fastLinkLeaving = inGroup + fastLinkLeaving = inGroup && p2p != null && ch != null if (!hosted.reported) orphanedFastLinkSsid = hosted.ssid - p2p.removeGroup(ch, quietListener("remove fast-link group")) + if (p2p != null && ch != null) p2p.removeGroup(ch, quietListener("remove fast-link group")) } if (joined?.linkId == linkId) { fastLinkJoined = null - fastLinkLeaving = inGroup - if (!joined.connected) p2p.cancelConnect(ch, quietListener("cancel fast-link join")) - p2p.removeGroup(ch, quietListener("leave fast-link group")) + fastLinkLeaving = inGroup && p2p != null && ch != null + if (p2p != null && ch != null) { + if (!joined.connected) p2p.cancelConnect(ch, quietListener("cancel fast-link join")) + p2p.removeGroup(ch, quietListener("leave fast-link group")) + } } } From 7969e25577c8f9c84069d4fa3ac40415b7fbe869 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:48:09 +0530 Subject: [PATCH 44/81] fix(bindings): name the wi-fi information entitlement an iphone join needs, and fail fast without it --- CHANGELOG.md | 3 ++- .../react-native/ios/WifiDirectManager.swift | 22 +++++++++++++++- bindings/react-native/src/index.ts | 5 ++-- ...fast-link-is-offered-inside-the-session.md | 8 ++++-- docs/mobile-permissions.md | 25 +++++++++++++------ 5 files changed, 49 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 392a96d83..afa405d34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,8 @@ Questions about a release, or about upgrading to one? Ask in the 2.5 s on two phones. Progress arrives as `fast_link_changed` events; the link ends after 60 s with nothing large to carry, when the iPhone app leaves the foreground, or on `closeFastLink`. An iOS app needs the Hotspot - Configuration entitlement, and an Android app `NEARBY_WIFI_DEVICES` (fine + Configuration and Access Wi-Fi Information entitlements (iOS 14 or later), + and an Android app `NEARBY_WIFI_DEVICES` (fine location below Android 13); see [mobile permissions](docs/mobile-permissions.md#fast-link). `wifiDirect.fastLink` decides how far an app takes part: `any` (the default) also hosts for a peer's request and joins an offer it did not ask diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 007a21f2d..c0bf20080 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -875,6 +875,8 @@ private final class FastLinkJoin { let deadline: TimeInterval /// iOS reported the join. var joined = false + /// Checks in a row in which iOS named no current network at all. + var networkUnknown = 0 /// The stream dialed toward the host for this link. weak var stream: AnyObject? @@ -898,6 +900,11 @@ private final class FastLinkJoin { extension WifiDirectManager { /// Gives a dial this long to become ready before it is tried again. private static let FAST_LINK_REDIAL: TimeInterval = 2.0 + /// Checks in a row, one per redial, in which iOS names no current + /// network before the join is given up as `failed`. Without the Access + /// Wi-Fi Information entitlement it never names one, and the link would + /// otherwise wait out its offer, two minutes, with nothing said. + private static let FAST_LINK_NETWORK_UNKNOWN_LIMIT = 5 /// Whether `error` is the hotspot error `code`. The domain is checked: /// another framework's error that shares the number would otherwise read @@ -1013,7 +1020,20 @@ extension WifiDirectManager { guard let self = self else { return } self.linkQueue.async { guard self.fastLink === link else { return } - if network?.ssid == link.ssid { + guard let network = network else { + link.networkUnknown += 1 + if link.networkUnknown >= Self.FAST_LINK_NETWORK_UNKNOWN_LIMIT { + self.emitDiagnostic("error", "Fast link: iOS does not say what network the phone is on; the app needs the Access Wi-Fi Information entitlement (com.apple.developer.networking.wifi-info)", context: [ + "linkId": link.linkId, + ]) + self.endFastLink(reason: "failed") + } else { + self.scheduleFastLinkRedial(link) + } + return + } + link.networkUnknown = 0 + if network.ssid == link.ssid { self.openFastLinkStream(link, port: port) } else { self.scheduleFastLinkRedial(link) diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index e7a251fdf..5efb959ad 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4617,8 +4617,9 @@ export class OfflineProtocol { * arrives as `fast_link_changed` events. On iOS the join shows a system * prompt and takes the phone off its own Wi-Fi while the link lasts, and * the link ends when the app leaves the foreground, so ask for it when a - * transfer is worth that. Needs the Hotspot Configuration entitlement on - * iOS and `NEARBY_WIFI_DEVICES` (fine location below Android 13) on Android. + * transfer is worth that. Needs the Hotspot Configuration and Access Wi-Fi + * Information entitlements on iOS 14 or later, and `NEARBY_WIFI_DEVICES` + * (fine location below Android 13) on Android. * * Rejects when the peer has not advertised support, there is no confirmed * session or live Bluetooth link to it, a peer stream already reaches it, diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 0b36beb66..3f4c16e7e 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -148,8 +148,12 @@ session, and only uses it. application should ask for a link when a transfer is worth that, and expect it to end when the user leaves. - An iOS application that uses it needs the Hotspot Configuration entitlement - (`com.apple.developer.networking.HotspotConfiguration`) and local-network - permission. An Android application needs `NEARBY_WIFI_DEVICES` on Android 13 + (`com.apple.developer.networking.HotspotConfiguration`), the Access Wi-Fi + Information entitlement (`com.apple.developer.networking.wifi-info`), and + local-network permission. The second is what lets + `NEHotspotNetwork.fetchCurrent` name the network the phone is on, which the + iPhone checks before it dials: a join can finish with no error while the + phone stays on its own Wi-Fi. An Android application needs `NEARBY_WIFI_DEVICES` on Android 13 and later, and fine location below it. - A fast link and Wi-Fi Direct group formation (`wifiDirect.autoAccept`) share the one group an Android device can own: while either holds it, the other diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index ece4fc13e..06e9adc9d 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -132,14 +132,23 @@ only when you are ready to show that flow. `requestFastLink` ([ADR 0038](adr/0038-a-fast-link-is-offered-inside-the-session.md)) brings up a Wi-Fi network between this device and a peer it meets over -Bluetooth. An iPhone joins the network the peer hosts, which needs the -**Hotspot Configuration** capability: add -`com.apple.developer.networking.HotspotConfiguration` to the app's -entitlements (Xcode adds it to the App ID with automatic signing), and keep -the local-network keys above, since the stream is a local-network connection. -Without the entitlement every join ends `failed`. An iPhone joins from iOS -14, which can say what network the phone is on; below it a request is refused -and a peer's offer answered `cannot_join`. +Bluetooth. An iPhone joins the network the peer hosts, which needs two +capabilities in the app's entitlements (Xcode adds each to the App ID with +automatic signing): + +- **Hotspot Configuration** + (`com.apple.developer.networking.HotspotConfiguration`), to join the + network. +- **Access Wi-Fi Information** (`com.apple.developer.networking.wifi-info`), + to confirm the phone is on that network before it dials. iOS can finish a + join with no error while the phone stays on its own Wi-Fi, and the dial + would then go to an address on the user's home network. + +Keep the local-network keys above too, since the stream is a local-network +connection. Without either entitlement every join ends `failed`, the second +with a diagnostic that names it. An iPhone joins from iOS 14, which can say +what network the phone is on; below it a request is refused and a peer's +offer answered `cannot_join`. iOS shows "“App” Wants to Join Wi‑Fi Network “DIRECT-…”?" on every join, and the phone leaves its own Wi-Fi while the link lasts. By default a peer's app From cdc112de49a5fb5c9c0db393c9b024021870403c Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:51:25 +0530 Subject: [PATCH 45/81] fix(protocol): offers a peer leaves unanswered pause it like a decline --- crates/offline-protocol/src/fast_link.rs | 114 ++++++++++++++++++++++- docs/security/threat-model.md | 7 +- docs/state-machines/fast-link.md | 8 +- 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index eeff02ec8..2d3e56e2d 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -516,7 +516,8 @@ struct Link { platform_engaged: bool, /// The peer knows of this link, so its end needs a `close` frame. peer_engaged: bool, - /// A host link brought up because the peer asked. + /// The peer started it: a host link brought up for its request, or a + /// join of an offer this device did not ask for. requested_by_peer: bool, } @@ -547,6 +548,13 @@ pub(crate) struct FastLinks { unanswered: VecDeque<(String, u8)>, /// Peers whose requests are refused, and since when ([`HOST_BACKOFF`]). host_backoff: VecDeque<(String, Instant)>, + /// Per peer, the offers it made without being asked that ended in a row + /// with no link up. Each was a join prompt on iOS, so + /// [`MAX_UNANSWERED_HOSTINGS`] of them start the decline pause, as a + /// Cancel does: a user who ignored the prompt, or a host that never + /// proved a stream, otherwise left the peer free to prompt again once + /// per offer lifetime. + unanswered_offers: VecDeque<(String, u8)>, /// Peers whose link ended after it was up. A transfer pinned to the /// slot for one of them can no longer reach it: its carrier is fixed when /// it starts, so it would retry on a dead slot until its retries ran out. @@ -581,6 +589,8 @@ impl FastLinks { // the peer's unanswered requests. self.declined.retain(|(declined, _)| declined != peer); self.unanswered.retain(|(unanswered, _)| unanswered != peer); + self.unanswered_offers + .retain(|(unanswered, _)| unanswered != peer); self.host_backoff .retain(|(backed_off, _)| backed_off != peer); if self.roles.can_host { @@ -883,7 +893,7 @@ impl FastLinks { offer: None, platform_engaged: false, peer_engaged: true, - requested_by_peer: false, + requested_by_peer: !asked, }); self.changed(None); } @@ -1056,6 +1066,49 @@ impl FastLinks { } } + /// Counts an offer `peer` made without being asked that ended: one that + /// came up resets the count; one that did not adds to it, unless this + /// device ended it for a reason of its own (its application closing it, + /// leaving the foreground) or its user declined, which pauses already. + /// [`MAX_UNANSWERED_HOSTINGS`] in a row start the decline pause. + fn count_offer( + &mut self, + peer: &str, + used: bool, + by_peer: bool, + reason: CloseReason, + now: Instant, + ) { + if used { + self.unanswered_offers + .retain(|(unanswered, _)| unanswered != peer); + return; + } + if reason == CloseReason::Declined + || (!by_peer && matches!(reason, CloseReason::Closed | CloseReason::Background)) + { + return; + } + let count = match self.unanswered_offers.iter_mut().find(|(p, _)| p == peer) { + Some((_, count)) => { + *count = count.saturating_add(1); + *count + } + None => { + if self.unanswered_offers.len() >= MAX_ENDED_REMEMBERED { + self.unanswered_offers.pop_front(); + } + self.unanswered_offers.push_back((peer.to_string(), 1)); + 1 + } + }; + if count >= MAX_UNANSWERED_HOSTINGS { + self.unanswered_offers + .retain(|(unanswered, _)| unanswered != peer); + self.record_decline(peer.to_string(), now); + } + } + fn record_decline(&mut self, peer: String, now: Instant) { if self.declined.len() >= MAX_ENDED_REMEMBERED { self.declined.pop_front(); @@ -1120,6 +1173,15 @@ impl FastLinks { { self.record_decline(link.peer.clone(), now); } + if link.requested_by_peer { + self.count_offer( + &link.peer, + link.state == FastLinkState::Up, + !tell_peer, + reason, + now, + ); + } } if link.platform_engaged { self.directives.push_back(PendingDirective { @@ -2335,6 +2397,54 @@ mod tests { ); } + #[test] + fn offers_left_unanswered_pause_the_peer_like_a_decline() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let mut now = Instant::now(); + // The Android offers a link nobody on the iPhone asked for; the + // prompt is ignored and the offer expires. + let offer = |android: &mut FastLinks, iphone: &mut FastLinks, seed, now| { + let id = android.request(HIGH, fresh(seed), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(android, LOW, iphone, HIGH, now, 0); + iphone.next_directive(now) + }; + + assert!(offer(&mut android, &mut iphone, 1, now).is_some()); + now += OFFER_TTL; + iphone.tick(now, |_| false); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + // One is forgiven. + assert!(offer(&mut android, &mut iphone, 2, now).is_some()); + now += OFFER_TTL; + iphone.tick(now, |_| false); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + + // The second in a row pauses the peer: no third prompt. + assert!(offer(&mut android, &mut iphone, 3, now).is_none()); + assert_eq!( + iphone.take_frames()[0].1.body, + FrameBody::Close { + reason: "declined".to_string() + } + ); + + // The iPhone's user asking ends the pause. + assert!(android.close(HIGH, now)); + android.take_frames(); + let asked = iphone.request(LOW, fresh(4), now).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + android.next_directive(now); + assert!(android.hosting(&asked, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + assert_eq!( + iphone.next_directive(now).unwrap().kind, + FastLinkDirectiveKind::Join + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 171d99870..a30fbb6cd 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1488,8 +1488,11 @@ address, so a link that proves nothing ends when its offer expires, at most not ask: an offer needs no request, unless the application set `wifiDirect.fastLink` to `requestedOnly`, which answers every offer it did not ask for `declined` and never shows it. Under the default, once the user declines, that peer's -offers are refused for ten minutes, and a second offer while one is on screen -is refused, so the most it gets is one prompt per ten minutes per session. An +offers are refused for ten minutes, and so they are once two offers in a row +it made unasked ended without a link coming up (a prompt ignored until the +offer expired, or a host that never proved a stream). A second offer while one +is on screen is refused too, so the most it gets is two prompts per ten +minutes per session. An Android joiner shows no prompt at all: Wi-Fi Direct joins a group by name and passphrase silently, so a session peer can move an Android device onto its group whenever it is in range, bounded by the same lifetime and by the diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 3588c1049..bfc64b029 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -97,7 +97,13 @@ cannot bring up a second network and prompt the user for it. ten minutes after this device's user declined a peer's network, that peer's offers are answered `declined` and never shown: each join on iOS is a system prompt, and without the pause a peer could put up another the moment one was -refused. The user's own request to that peer ends the pause. A second offer +refused. Two offers in a row that the peer made unasked and that ended +without a link coming up start the same pause, whatever the peer's reason or +the offer's expiry, unless this device ended them itself (its application +closing the link, leaving the foreground): a prompt the user ignores is never +declined, and without this the peer could prompt again once per offer +lifetime. One is forgiven, a link that comes up clears the count, and the +user's own request to that peer ends the pause. A second offer from the peer while one is being joined or is up is answered `busy` and the first stands: an honest host's new network follows its own `close`, and a swap would let a peer re-offer while each prompt is on screen, so that no From 6d1961461f2ba30cd90665b5d1d8c276d0d8e752 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 09:53:02 +0530 Subject: [PATCH 46/81] fix(protocol): a hosted fast link that is up is never swapped for an offer --- crates/offline-protocol/src/fast_link.rs | 55 ++++++++++++++++++++++++ docs/state-machines/fast-link.md | 6 ++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 2d3e56e2d..b5dd9c681 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -825,6 +825,14 @@ impl FastLinks { asked = true; match link.role { FastLinkRole::Host => { + // A link already up is never torn down for an offer: + // the tie-break below is for two hosts racing, and an + // offer once one is up would swap a working link for a + // second group, which the Android joins with no prompt. + if link.state == FastLinkState::Up { + self.reply_close(peer, link_id, CloseReason::Busy); + return; + } // Both are hosting for each other. The lower address // keeps hosting; the higher closes its own and joins. if local.as_bytes() < peer.as_bytes() { @@ -2445,6 +2453,53 @@ mod tests { ); } + #[test] + fn a_hosted_link_that_is_up_is_never_swapped_for_an_offer() { + let t0 = Instant::now(); + // HIGH hosts and its link comes up; the lower-addressed peer then + // offers a network of its own, which the tie-break would favour. + let mut high = machine(host_roles()); + let id = high.request(LOW, fresh(1), t0).unwrap(); + high.next_directive(t0); + assert!(high.hosting(&id, "192.168.49.1", 8988, t0, 0)); + high.take_frames(); + high.stream_proved(LOW, t0); + high.take_changes(); + + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + let other = fresh(2).link_id; + high.on_frame( + LOW, + HIGH, + Frame::new(&other, FrameBody::Offer(offer)), + fresh(3), + t0, + 0, + ); + assert_eq!(high.peer(), Some(LOW)); + assert!(high.take_changes().is_empty(), "the link that is up stands"); + assert!(!high.has_directives(), "no join, no close"); + assert_eq!( + high.take_frames(), + [( + LOW.to_string(), + Frame::new( + &other, + FrameBody::Close { + reason: "busy".to_string() + } + ) + )] + ); + } + #[test] fn a_host_address_off_the_network_is_never_offered() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index bfc64b029..ad826d558 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -111,7 +111,11 @@ decline is ever reported and the pause never begins. An offer that fails validation (below) is answered `close` (`invalid`) and nothing else happens. When both devices are hosting for each other, the lower address keeps hosting: the higher one closes its own link and joins, and the lower one -ignores the higher one's offer, which its owner is about to withdraw. +ignores the higher one's offer, which its owner is about to withdraw. A host +whose link is already up answers any offer `busy`, as a joiner does: the +tie-break is for two hosts racing, and applied once a link is up it would +swap a working link for a second group, which an Android joins with no +prompt. **A `close` arrives.** It ends the link with that id, if there is one, and is never answered. From ab2ff62d27a75f7cbd1d1f360b90d591d851fe7e Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:02:25 +0530 Subject: [PATCH 47/81] fix(protocol): a host closing its own unasked offers declined still counts toward the pause --- crates/offline-protocol/src/fast_link.rs | 57 +++++++++++++++++++++--- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index b5dd9c681..b5e5b5e33 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -1075,9 +1075,10 @@ impl FastLinks { } /// Counts an offer `peer` made without being asked that ended: one that - /// came up resets the count; one that did not adds to it, unless this - /// device ended it for a reason of its own (its application closing it, - /// leaving the foreground) or its user declined, which pauses already. + /// came up resets the count; one that did not adds to it, whatever the + /// peer's reason, unless this device ended it itself (its application + /// closing it, leaving the foreground, or its user declining, which + /// pauses already). /// [`MAX_UNANSWERED_HOSTINGS`] in a row start the decline pause. fn count_offer( &mut self, @@ -1092,8 +1093,14 @@ impl FastLinks { .retain(|(unanswered, _)| unanswered != peer); return; } - if reason == CloseReason::Declined - || (!by_peer && matches!(reason, CloseReason::Closed | CloseReason::Background)) + // Only this device's own ends are skipped. A host never has cause to + // close its own offer `declined`, which only a joiner's user does; + // skipping the peer's let it offer and close that way forever. + if !by_peer + && matches!( + reason, + CloseReason::Declined | CloseReason::Closed | CloseReason::Background + ) { return; } @@ -2453,6 +2460,46 @@ mod tests { ); } + #[test] + fn a_host_closing_its_own_offers_declined_is_still_paused() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + for seed in [1, 2] { + let id = android.request(HIGH, fresh(seed), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + assert!(iphone.next_directive(now).is_some(), "offer {seed} prompts"); + // The host ends its own offer with a reason only a joiner gives. + iphone.on_frame( + LOW, + HIGH, + Frame::new( + &id, + FrameBody::Close { + reason: "declined".to_string(), + }, + ), + fresh(seed + 10), + now, + 0, + ); + assert!(iphone.peer().is_none()); + assert!(android.close(HIGH, now)); + android.take_frames(); + iphone.take_frames(); + } + let id = android.request(HIGH, fresh(3), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + assert!( + !iphone.has_directives(), + "the third unasked offer is never shown" + ); + } + #[test] fn a_hosted_link_that_is_up_is_never_swapped_for_an_offer() { let t0 = Instant::now(); From a416d03967c9e7f3aa5dec9cc00c4d2150ebae4b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:05:57 +0530 Subject: [PATCH 48/81] fix(protocol): asking again after a lost offer joins the network still offered --- crates/offline-protocol/src/fast_link.rs | 44 +++++++++++++++++++++++- docs/state-machines/fast-link.md | 6 +++- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index b5e5b5e33..9760070d2 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -709,7 +709,18 @@ impl FastLinks { now: Instant, now_ms: i64, ) { - if self.ended_recently(&frame.link, now) { + // A late offer still answers a request this device is waiting on now, + // from the same peer: the user has just asked again, so the prompt is + // wanted, and a host still holding the old network answers the new + // request with it. Refused, the retry after a lost offer met a host + // that resent the old one, and ended `no_offer` with nothing shown. + let answers_request = matches!(frame.body, FrameBody::Offer(_)) + && self.link.as_ref().is_some_and(|link| { + link.peer == peer + && link.role == FastLinkRole::Join + && link.state == FastLinkState::Requested + }); + if !answers_request && self.ended_recently(&frame.link, now) { // A late request needs no answer: its sender has given up on it. // A late offer gets one, so the host takes its network down. if matches!(frame.body, FrameBody::Offer(_)) { @@ -1835,6 +1846,37 @@ mod tests { assert!(android.next_directive(t0).is_none(), "one network, not two"); } + #[test] + fn asking_again_after_a_lost_offer_joins_the_network_still_up() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let first = iphone.request(LOW, fresh(1), t0).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, t0, 0); + android.next_directive(t0); + assert!(android.hosting(&first, "192.168.49.1", 8988, t0, 0)); + // The offer is lost, and the requester gives up. + android.take_frames(); + iphone.tick(t0 + REQUEST_TIMEOUT, |_| false); + iphone.take_frames(); + + // The user asks again under a new id; the host, still offering, sends + // the network it already has. + let later = t0 + REQUEST_TIMEOUT; + let second = iphone.request(LOW, fresh(2), later).unwrap(); + assert_ne!(first, second); + deliver(&mut iphone, HIGH, &mut android, LOW, later, 0); + deliver(&mut android, LOW, &mut iphone, HIGH, later, 0); + + let join = iphone.next_directive(later).unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, first); + assert!(iphone.take_frames().is_empty(), "no `expired` to the host"); + iphone.stream_proved(LOW, later); + android.stream_proved(HIGH, later); + assert_eq!(states(&mut android).last(), Some(&FastLinkState::Up)); + } + #[test] fn a_late_offer_for_a_link_given_up_on_is_refused_not_joined() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index ad826d558..259794375 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -126,7 +126,11 @@ request is dropped; an offer is answered `close` (`expired`), so the host takes its network down, and is never joined. On two phones a request delayed 63 s reached the host after the requester had given up, and before this rule its offer prompted the requester's user to join a network that had -already been removed. +already been removed. The one exception is an offer from a peer this device +is waiting on now, its own request to that peer still open: the user has just +asked again, so the prompt is wanted, and the offer answers the new request. +A host still offering the old network sends it again for the new request, and +refusing it ended the user's second attempt `no_offer` with nothing shown. An offer is valid when its name is 1 to 32 bytes, its passphrase 8 to 63 printable ASCII characters, its host a private or link-local IP literal, its From 9598401a547733b20eb7ee2d450ce3483f6668d8 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:06:06 +0530 Subject: [PATCH 49/81] fix(protocol): a device that cannot join refuses an offer before giving up what it holds --- crates/offline-protocol/src/fast_link.rs | 32 +++++++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 9760070d2..9b754cc8c 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -825,6 +825,13 @@ impl FastLinks { self.reply_close(peer, link_id, CloseReason::Declined); return; } + // Before anything held is given up: a device that cannot join would + // otherwise drop its waiting request with no `closed`, or end the + // link it hosts in the tie-break below, and then refuse the offer. + if !self.roles.can_join { + self.reply_close(peer, link_id, CloseReason::CannotJoin); + return; + } // Whether this device's application asked for a link with the peer: // its request is waiting, or it is hosting for the peer itself. let mut asked = false; @@ -878,10 +885,6 @@ impl FastLinks { } } } - if !self.roles.can_join { - self.reply_close(peer, link_id, CloseReason::CannotJoin); - return; - } if !asked && !self.roles.accept_unrequested { self.reply_close(peer, link_id, CloseReason::Declined); return; @@ -1877,6 +1880,27 @@ mod tests { assert_eq!(states(&mut android).last(), Some(&FastLinkState::Up)); } + #[test] + fn a_device_that_can_no_longer_join_keeps_what_it_holds() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let id = iphone.request(LOW, fresh(1), t0).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, t0, 0); + iphone.take_changes(); + iphone.set_roles(FastLinkRoles::default()); + android.next_directive(t0); + assert!(android.hosting(&id, "192.168.49.1", 8988, t0, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, t0, 0); + + assert_eq!(iphone.peer(), Some(LOW), "the request still waits"); + assert!(iphone.take_changes().is_empty()); + assert!(!iphone.has_directives()); + // Its own timer ends it, with the one `closed` the application waits on. + iphone.tick(t0 + REQUEST_TIMEOUT, |_| false); + assert_eq!(states(&mut iphone), [FastLinkState::Closed]); + } + #[test] fn a_late_offer_for_a_link_given_up_on_is_refused_not_joined() { let t0 = Instant::now(); From dce48279899470dd3be5c1aa268701fa5b488dae Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:18:21 +0530 Subject: [PATCH 50/81] fix(bindings): an android host removes a fast-link group its dead process left --- .../com/offlineprotocol/WifiDirectManager.kt | 46 ++++++++++++++++++- docs/state-machines/fast-link.md | 7 +++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 410d9b266..05ae9f268 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -90,6 +90,8 @@ class WifiDirectManager( companion object { private const val TAG = "WifiDirectManager" + private const val FAST_LINK_PREFS = "offline_protocol_fast_link" + private const val HOSTED_FAST_LINK_GROUP = "hosted_group" // Fallback interval for message polling. Primary send path is event-driven // via onMessagesAvailable(); this timer only catches edge cases. @@ -587,8 +589,30 @@ class WifiDirectManager( if (channel == null) return wifiP2pManager?.requestConnectionInfo(channel) { info -> if (info?.groupFormed == true && state == TransportState.RUNNING) { - emitDiagnostic("info", "Joining a group formed before start") - handleConnectionChanged(true) + val adopt = { + emitDiagnostic("info", "Joining a group formed before start") + handleConnectionChanged(true) + } + val leftover = fastLinkPrefs.getString(HOSTED_FAST_LINK_GROUP, null) + if (leftover == null || !info.isGroupOwner) { + adopt() + } else { + wifiP2pManager?.requestGroupInfo(channel) { group -> + if (group != null && group.isGroupOwner && group.networkName == leftover) { + // A fast link's group from a process that died: + // its link went with the process, and adopted it + // would stay on the air with no timer, refusing + // every later link. + recordHostedFastLinkGroup(null) + emitDiagnostic("info", "Fast link: removing a group left by an earlier run") + wifiP2pManager?.removeGroup(channel, quietListener("remove leftover fast-link group")) + } else { + adopt() + } + } + } + } else if (state == TransportState.RUNNING) { + recordHostedFastLinkGroup(null) } } } @@ -1558,6 +1582,7 @@ class WifiDirectManager( } val hosted = FastLinkHosted(directive.linkId, directive.peerId, ssid) fastLinkHosted = hosted + recordHostedFastLinkGroup(ssid) emitDiagnostic("info", "Fast link: bringing up a network", mapOf("linkId" to directive.linkId)) p2p.createGroup(ch, config, object : WifiP2pManager.ActionListener { override fun onSuccess() {} @@ -1694,6 +1719,22 @@ class WifiDirectManager( } } + /** + * The name of the group this device brought up for a fast link, kept on + * disk until the group is seen gone. The group belongs to the system, not + * the process, so one left by a process that died outlives it, and on the + * next start [adoptExistingGroup] removes it rather than adopting it. + */ + private val fastLinkPrefs by lazy { + context.getSharedPreferences(FAST_LINK_PREFS, Context.MODE_PRIVATE) + } + + private fun recordHostedFastLinkGroup(ssid: String?) { + val edit = fastLinkPrefs.edit() + if (ssid == null) edit.remove(HOSTED_FAST_LINK_GROUP) else edit.putString(HOSTED_FAST_LINK_GROUP, ssid) + edit.apply() + } + /** Removes the group a closed link brought up after it was closed. */ @SuppressLint("MissingPermission") private fun removeOrphanedFastLinkGroup() { @@ -1709,6 +1750,7 @@ class WifiDirectManager( /** This device left whatever group it was in. */ private fun fastLinkGroupGone() { fastLinkLeaving = false + recordHostedFastLinkGroup(null) parkedFastLinkJoin?.let { parked -> parkedFastLinkJoin = null try { diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 259794375..f0a19620a 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -173,6 +173,13 @@ application returned, with nothing bounding it. Stopping it ends a link with `closed`, for the same reason and one more: an engine started again would find the old link still held and answer every request `busy`. +A host whose process dies ends nothing: an Android group belongs to the +system, not the process, and stays on the air. The host's platform keeps the +group's name on disk until it sees the group gone, and on its next start +removes an owned group of that name rather than joining the socket layer to +it as an ordinary group, which left it up with no timer and refused every +later link. + A joiner's platform that is about to lose the network reports it as `ended` first: on iOS, leaving the foreground, after which iOS disconnects at 15 s whatever the engine thinks. Without the report the host learns from TCP From a7ee0605fcfcfaec585f16c55e489b7fbce1ee94 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:20:35 +0530 Subject: [PATCH 51/81] docs: say a fast link's events are matched by peer, since its id can change once --- .../csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs | 2 +- .../src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs | 2 +- .../src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part01.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part02.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part03.g.cs | 2 +- .../Generated/ProtocolEngine.Static.g.cs | 2 +- bindings/python/offline_protocol_sdk/local_api/table.py | 2 +- bindings/react-native/src/index.ts | 4 +++- crates/offline-protocol-uniffi/src/offline_protocol.udl | 4 +++- crates/offline-protocol/src/events.rs | 5 ++++- crates/offline-protocol/src/protocol/fast_link.rs | 4 +++- docs/state-machines/fast-link.md | 6 +++++- 13 files changed, 26 insertions(+), 13 deletions(-) diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index b70af05a3..faeed711d 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index 11b44038a..448e84882 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index 68270172c..84f34765b 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index c3fdc10ba..3aeaf279f 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index c1c75b489..810c74a3d 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 786839376..62158b776 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index 50b98ba66..e20a60a69 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = 64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a +// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 // Do not edit. #nullable enable diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index a8e5d03f0..fbda42581 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "64ab3614ff8f0c44ede4b975aa90f81cca642b688f19a7c9b59817e6fc02892a" +UDL_SHA256 = "b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index 5efb959ad..7317b45a5 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4614,7 +4614,9 @@ export class OfflineProtocol { * `media_send_failed`; send it again and it goes over what remains. * * Resolves with the link id as soon as the first step is taken; the outcome - * arrives as `fast_link_changed` events. On iOS the join shows a system + * arrives as `fast_link_changed` events for the peer. Match them by + * `peerId`, not by this id: a device holds one link at a time, and the id + * changes once when the host answers with a network it already had. On iOS the join shows a system * prompt and takes the phone off its own Wi-Fi while the link lasts, and * the link ends when the app leaves the foreground, so ask for it when a * transfer is worth that. Needs the Hotspot Configuration and Access Wi-Fi diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index 785e61cce..14d487f8e 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1421,7 +1421,9 @@ interface OfflineProtocol { // session, and the stream over it fills the peer-stream slot, so traffic // moves to it by ordinary transport selection. Returns the link id as // soon as the first step is taken; the outcome arrives as - // `fast_link_changed` events. On iOS a join shows a system prompt and + // `fast_link_changed` events for the peer. Track the link by peer: the + // id changes once when the host answers with a network it already had. + // On iOS a join shows a system prompt and // takes the phone off its own Wi-Fi while the link lasts, so this is the // application's call, never automatic. Refused when the peer has not // advertised it, there is no confirmed session or live direct link, a diff --git a/crates/offline-protocol/src/events.rs b/crates/offline-protocol/src/events.rs index e82aa5e0c..4e8f89573 100644 --- a/crates/offline-protocol/src/events.rs +++ b/crates/offline-protocol/src/events.rs @@ -765,7 +765,10 @@ pub enum Event { /// hosts for a peer, or joins from it, brought up through their session. /// /// `request_fast_link` returns as soon as its first step is taken; this is - /// how the application learns the outcome. It never carries a network + /// how the application learns the outcome. Match it by `peer_id`, of + /// which a device holds one link at a time: the `link_id` changes once + /// when the host answers with a network it already had, and the request's + /// own id then sees no further event. It never carries a network /// name or a passphrase. The traffic itself moves to the link by the /// ordinary transport selection, which `TransportSwitched` reports. FastLinkChanged { diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 11830d46a..85c5bd657 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -45,7 +45,9 @@ impl OfflineProtocol { /// /// Returns as soon as the first step is taken: this device starts /// hosting when it can, and otherwise asks the peer to host. The outcome - /// arrives as `FastLinkChanged` events. Refused when the peer has not + /// arrives as `FastLinkChanged` events for `peer`, matched by peer rather + /// than by this id, which changes once when the host answers with a + /// network it already had. Refused when the peer has not /// advertised the capability, there is no confirmed session or no live /// direct link to it, a peer stream already proves it, this device can /// neither host nor join, or a link with another peer is held. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index f0a19620a..788a1b90b 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -190,7 +190,11 @@ keepalive, about 40 s later. `fast_link_changed` carries the peer, the link id, the role (`host` or `join`), the state (one of the six above) and, on `closed`, the reason. It is how the application learns the outcome of `request_fast_link`, which returns -as soon as the first step is taken. It never carries a network name or a +as soon as the first step is taken. The application matches it by peer, of +which a device holds one link at a time, not by the id the request returned: +when the host answers with a network it already had (a request asked again +after a lost offer), the link takes the host's id and the request's id sees +no further event. It never carries a network name or a passphrase. ## What the shapes prevent From 8357c0877cfa56944e04cf84a38617e5f14d0502 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:22:04 +0530 Subject: [PATCH 52/81] fix(bindings): an explicit null keeps the ios fast-link setting, as on android --- bindings/react-native/ios/WifiDirectManager.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index c0bf20080..5b52c01d2 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -1100,7 +1100,8 @@ public enum FastLinkMode: Equatable { /// enable that does not mention `fastLink` keeps the setting. An unknown /// value is `.off`, so a typo never widens what the application allowed. static func parse(_ value: Any?, current: FastLinkMode) -> FastLinkMode { - guard let value = value else { return current } + // An explicit JavaScript null keeps the setting too, as on Android. + guard let value = value, !(value is NSNull) else { return current } switch value as? String { case "any": return .any case "requestedOnly": return .requestedOnly From b6f13ec9335327b8c7ac87fd655a6af87a96ea78 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:22:04 +0530 Subject: [PATCH 53/81] docs: correct the fast link's activity size and where an android joiner dials --- crates/offline-protocol/src/fast_link.rs | 4 ++-- docs/spec/stream-framing.md | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 9b754cc8c..e15c29edc 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -47,8 +47,8 @@ pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); /// in flight, before it ends. It costs the joiner its own Wi-Fi. pub const IDLE_LIMIT: Duration = Duration::from_secs(60); -/// The smallest body that counts as activity for [`IDLE_LIMIT`]: half a media -/// chunk on the slot. Presence, receipts and chat are smaller and go over +/// The smallest body that counts as activity for [`IDLE_LIMIT`]: 16 KiB, well +/// under a media chunk on the slot and well over any control frame. Presence, receipts and chat are smaller and go over /// Bluetooth LE perfectly well, and counting them kept a link up for as long /// as an application sent presence every 15 s (two phones, ADR 0038). pub const ACTIVITY_MIN_BYTES: usize = 16 * 1024; diff --git a/docs/spec/stream-framing.md b/docs/spec/stream-framing.md index 8037debac..9b77195ab 100644 --- a/docs/spec/stream-framing.md +++ b/docs/spec/stream-framing.md @@ -315,9 +315,10 @@ Where two devices share no network, one may bring a network up for the other on request, with its credentials sent inside their session: the fast link ([ADR 0038](../adr/0038-a-fast-link-is-offered-inside-the-session.md)). Nothing in this chapter changes over it. There is no discovery record: the joiner -dials the address and port the offer named, with the host's address as its -claim (step four above), and the host admits no other proved address on the -network it made. +dials the port the offer named, at the address it named (an iPhone) or at the +group owner's own address (an Android, which stays on its own Wi-Fi as well), +with the host's address as its claim (step four above), and the host admits +no other proved address on the network it made. ## Position among the transports From 30cfa654ac2e85e612d38e380c47b5e7760f8f1c Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:35:34 +0530 Subject: [PATCH 54/81] fix(protocol): a peer that asked for a fast link cannot then offer one around the limits --- crates/offline-protocol/src/fast_link.rs | 62 +++++++++++++++++++++++- docs/state-machines/fast-link.md | 6 ++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index e15c29edc..2a169e0a1 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -847,7 +847,12 @@ impl FastLinks { // the tie-break below is for two hosts racing, and an // offer once one is up would swap a working link for a // second group, which the Android joins with no prompt. - if link.state == FastLinkState::Up { + // Nor is one hosted because the peer asked: a peer that + // asks cannot host, so its offer is never honest, and + // the tie-break below would end this link uncounted and + // join an offer marked as asked for, around both the + // host backoff and the pause on unasked offers. + if link.state == FastLinkState::Up || link.requested_by_peer { self.reply_close(peer, link_id, CloseReason::Busy); return; } @@ -2566,6 +2571,61 @@ mod tests { ); } + #[test] + fn a_peer_that_asked_cannot_then_offer_around_the_limits() { + let t0 = Instant::now(); + // HIGH can host and join, as an Android; LOW asks it to host and then + // offers a network of its own, which the tie-break would favour. + let mut high = machine(host_roles()); + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + }; + let id = fresh(1).link_id; + high.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Request), + fresh(2), + t0, + 0, + ); + assert_eq!( + high.next_directive(t0).unwrap().kind, + FastLinkDirectiveKind::Host + ); + high.take_changes(); + let other = fresh(3).link_id; + high.on_frame( + LOW, + HIGH, + Frame::new(&other, FrameBody::Offer(offer)), + fresh(4), + t0, + 0, + ); + + assert_eq!(high.peer(), Some(LOW), "still hosting for the request"); + assert!(high.take_changes().is_empty()); + assert!(!high.has_directives(), "no join"); + assert_eq!( + high.take_frames(), + [( + LOW.to_string(), + Frame::new( + &other, + FrameBody::Close { + reason: "busy".to_string() + } + ) + )] + ); + } + #[test] fn a_hosted_link_that_is_up_is_never_swapped_for_an_offer() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 788a1b90b..89f3e1902 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -115,7 +115,11 @@ ignores the higher one's offer, which its owner is about to withdraw. A host whose link is already up answers any offer `busy`, as a joiner does: the tie-break is for two hosts racing, and applied once a link is up it would swap a working link for a second group, which an Android joins with no -prompt. +prompt. So does a host whose link the peer asked for: a peer that asks +cannot host, so its offer is never honest, and acted on it ended the hosted +link uncounted and joined an offer taken as asked for, so a peer that asked +and then offered, over and over, met neither the host backoff nor the pause +on unasked offers. **A `close` arrives.** It ends the link with that id, if there is one, and is never answered. From bb15fef170298a78f8bf4e17f65927fb7a61c7b0 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:36:35 +0530 Subject: [PATCH 55/81] fix(bindings): an ios join that never reaches the offered network says so --- bindings/react-native/ios/WifiDirectManager.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 5b52c01d2..002884afe 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -901,9 +901,11 @@ extension WifiDirectManager { /// Gives a dial this long to become ready before it is tried again. private static let FAST_LINK_REDIAL: TimeInterval = 2.0 /// Checks in a row, one per redial, in which iOS names no current - /// network before the join is given up as `failed`. Without the Access - /// Wi-Fi Information entitlement it never names one, and the link would - /// otherwise wait out its offer, two minutes, with nothing said. + /// network before the join is given up as `failed`. It names none while + /// the phone is on a network this app did not configure, so a join that + /// never happened, and none at all without the Access Wi-Fi Information + /// entitlement; either way the link would otherwise wait out its offer, + /// two minutes, with nothing said. private static let FAST_LINK_NETWORK_UNKNOWN_LIMIT = 5 /// Whether `error` is the hotspot error `code`. The domain is checked: @@ -1023,7 +1025,7 @@ extension WifiDirectManager { guard let network = network else { link.networkUnknown += 1 if link.networkUnknown >= Self.FAST_LINK_NETWORK_UNKNOWN_LIMIT { - self.emitDiagnostic("error", "Fast link: iOS does not say what network the phone is on; the app needs the Access Wi-Fi Information entitlement (com.apple.developer.networking.wifi-info)", context: [ + self.emitDiagnostic("error", "Fast link: the phone is not on the offered network, or the app lacks the Access Wi-Fi Information entitlement (com.apple.developer.networking.wifi-info)", context: [ "linkId": link.linkId, ]) self.endFastLink(reason: "failed") From 5fce1942bc663e655125b140b1a738ce30f55184 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:50:22 +0530 Subject: [PATCH 56/81] fix(protocol): a fast link that came up and carried nothing still counts toward the limits --- crates/offline-protocol/src/fast_link.rs | 96 +++++++++++++++++++----- docs/security/threat-model.md | 14 ++-- docs/state-machines/fast-link.md | 14 ++-- 3 files changed, 95 insertions(+), 29 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 2a169e0a1..567d06956 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -519,6 +519,12 @@ struct Link { /// The peer started it: a host link brought up for its request, or a /// join of an offer this device did not ask for. requested_by_peer: bool, + /// The link carried a body of [`ACTIVITY_MIN_BYTES`] or more, or a + /// transfer over it. Only such a link counts as used toward the host + /// backoff and the pause on unasked offers: counting any link that came + /// up let a peer join, carry nothing, let it idle out and ask again, + /// holding the group without end. + carried: bool, } /// The machine. One link at a time (invariant 3). @@ -616,6 +622,7 @@ impl FastLinks { platform_engaged: false, peer_engaged: true, requested_by_peer: false, + carried: false, }); self.changed(None); Ok(id) @@ -648,6 +655,7 @@ impl FastLinks { platform_engaged: false, peer_engaged, requested_by_peer: peer_engaged, + carried: false, }); self.changed(None); } @@ -921,6 +929,7 @@ impl FastLinks { platform_engaged: false, peer_engaged: true, requested_by_peer: !asked, + carried: false, }); self.changed(None); } @@ -1017,6 +1026,7 @@ impl FastLinks { if let Some(link) = self.link.as_mut() { if link.peer == peer { link.last_activity = now; + link.carried = true; } } } @@ -1035,6 +1045,7 @@ impl FastLinks { FastLinkState::Up => { if busy(&link.peer) { link.last_activity = now; + link.carried = true; None } else if now.saturating_duration_since(link.last_activity) >= IDLE_LIMIT { Some(CloseReason::Idle) @@ -1049,9 +1060,10 @@ impl FastLinks { } } - /// Counts a link hosted for `peer`'s request that ended: one its stream - /// used resets the count; one that went unused adds to it when it expired - /// or the peer ended it, whatever reason the peer gave; and + /// Counts a link hosted for `peer`'s request that ended: one that carried + /// something ([`Link::carried`]) resets the count; one that did not adds + /// to it when it expired, went idle or lost its stream, or the peer ended + /// it, whatever reason the peer gave; and /// [`MAX_UNANSWERED_HOSTINGS`] in a row start [`HOST_BACKOFF`]. Ends this /// device caused (its platform failing, its tie-break, its user) are not /// the peer's to answer for. Counting only `expired` let a peer close @@ -1068,7 +1080,14 @@ impl FastLinks { self.unanswered.retain(|(unanswered, _)| unanswered != peer); return; } - if !by_peer && reason != CloseReason::Expired { + // This device's own ends that still name the peer's silence count: + // its offer expiring, the stream it proved going idle or dropping. + if !by_peer + && !matches!( + reason, + CloseReason::Expired | CloseReason::Idle | CloseReason::Lost + ) + { return; } let count = match self.unanswered.iter_mut().find(|(p, _)| p == peer) { @@ -1094,7 +1113,8 @@ impl FastLinks { } /// Counts an offer `peer` made without being asked that ended: one that - /// came up resets the count; one that did not adds to it, whatever the + /// carried something ([`Link::carried`]) resets the count; one that did + /// not, up or not, adds to it, whatever the /// peer's reason, unless this device ended it itself (its application /// closing it, leaving the foreground, or its user declining, which /// pauses already). @@ -1185,13 +1205,7 @@ impl FastLinks { self.released.push_back(link.peer.clone()); } if link.role == FastLinkRole::Host && link.requested_by_peer { - self.count_hosting( - &link.peer, - link.state == FastLinkState::Up, - !tell_peer, - reason, - now, - ); + self.count_hosting(&link.peer, link.carried, !tell_peer, reason, now); } if link.role == FastLinkRole::Join { if self.ended_joins.len() >= MAX_ENDED_REMEMBERED { @@ -1208,13 +1222,7 @@ impl FastLinks { self.record_decline(link.peer.clone(), now); } if link.requested_by_peer { - self.count_offer( - &link.peer, - link.state == FastLinkState::Up, - !tell_peer, - reason, - now, - ); + self.count_offer(&link.peer, link.carried, !tell_peer, reason, now); } } if link.platform_engaged { @@ -2571,6 +2579,56 @@ mod tests { ); } + #[test] + fn links_that_come_up_and_carry_nothing_count_as_unanswered() { + let mut android = machine(host_roles()); + let mut now = Instant::now(); + // The peer asks, joins, proves its stream, carries nothing, and lets + // the link idle out; then asks again. + let mut round = |android: &mut FastLinks, seed, now: Instant, carry: bool| { + let id = fresh(seed).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(seed + 10), + now, + 0, + ); + if android.next_directive(now).map(|d| d.kind) != Some(FastLinkDirectiveKind::Host) { + return false; + } + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + android.stream_proved(HIGH, now); + if carry { + android.activity(HIGH, ACTIVITY_MIN_BYTES, now); + } + android.tick(now + IDLE_LIMIT, |_| false); + assert!(android.peer().is_none(), "ended idle"); + android.take_frames(); + android.next_directive(now); + true + }; + + // A link that carried something resets the count. + assert!(round(&mut android, 1, now, false)); + now += IDLE_LIMIT; + assert!(round(&mut android, 2, now, true)); + now += IDLE_LIMIT; + assert!(round(&mut android, 3, now, false)); + now += IDLE_LIMIT; + // Two in a row that carried nothing: the next request is refused. + assert!(round(&mut android, 4, now, false)); + now += IDLE_LIMIT; + assert!(!round(&mut android, 5, now, false)); + assert_eq!( + android.take_frames()[0].1.body, + FrameBody::Close { + reason: "busy".to_string() + } + ); + } + #[test] fn a_peer_that_asked_cannot_then_offer_around_the_limits() { let t0 = Instant::now(); diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index a30fbb6cd..d09402673 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1489,8 +1489,9 @@ not ask: an offer needs no request, unless the application set `wifiDirect.fastLink` to `requestedOnly`, which answers every offer it did not ask for `declined` and never shows it. Under the default, once the user declines, that peer's offers are refused for ten minutes, and so they are once two offers in a row -it made unasked ended without a link coming up (a prompt ignored until the -offer expired, or a host that never proved a stream). A second offer while one +it made unasked ended having carried nothing (a prompt ignored until the +offer expired, a host that never proved a stream, or a link that came up and +idled out). A second offer while one is on screen is refused too, so the most it gets is two prompts per ten minutes per session. An Android joiner shows no prompt at all: Wi-Fi Direct joins a group by name and @@ -1505,9 +1506,12 @@ no route onward. a link from forming, which is no more than they could already do to the messages themselves. The traffic stays on Bluetooth. A session peer can make an Android host bring up a group by asking, and holds the device's one group -(and so its own group formation) while it lasts: at most two offer lifetimes, -about four minutes, before the host stops answering that peer's requests for -ten minutes. +(and so its own group formation) while it lasts: at most two links that carry +nothing, each an offer lifetime and, if joined, the idle limit after it +(about six minutes in all), before the host stops answering that peer's +requests for ten minutes. A link that came up counts toward this unless it +carried a body of 16 KiB or a transfer, so joining and idling does not reset +it. **Why it stands:** a network that does not broadcast its existence cannot be joined by an iPhone that was handed its name, and the session is the only diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 89f3e1902..a2567fd7a 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -82,9 +82,13 @@ for go ahead and no join prompt or group appears that it did not want. One that already offered this peer a link sends the same offer again, since the request means the first one was lost. Otherwise it starts hosting under the request's link id, unless two links it hosted in a row for that peer's -requests went unused, expiring or ended by the peer (whatever reason it gives) -with no stream from it: then it answers `busy` for ten minutes, so a peer that never joins cannot keep a group on the air, and the -device's own group formation locked out, by asking again each time. One miss +requests carried nothing (no body of 16 KiB or more, no transfer) and ended by +expiring, going idle, losing their stream, or at the peer's hand, whatever +reason it gives: then it answers `busy` for ten minutes, so a peer cannot keep +a group on the air, and the device's own group formation locked out, by +asking again each time. A link that came up counts the same as one never +joined unless it carried something: otherwise a peer could join, carry +nothing, let the link idle out and ask again, without end. One miss is forgiven, so a user who did not tap in time can ask again, and this device's own request to the peer ends the pause. @@ -98,11 +102,11 @@ ten minutes after this device's user declined a peer's network, that peer's offers are answered `declined` and never shown: each join on iOS is a system prompt, and without the pause a peer could put up another the moment one was refused. Two offers in a row that the peer made unasked and that ended -without a link coming up start the same pause, whatever the peer's reason or +having carried nothing, up or not, start the same pause, whatever the peer's reason or the offer's expiry, unless this device ended them itself (its application closing the link, leaving the foreground): a prompt the user ignores is never declined, and without this the peer could prompt again once per offer -lifetime. One is forgiven, a link that comes up clears the count, and the +lifetime. One is forgiven, a link that carries something clears the count, and the user's own request to that peer ends the pause. A second offer from the peer while one is being joined or is up is answered `busy` and the first stands: an honest host's new network follows its own `close`, and a From 5b277b550f3a0b560bf636d6d482277cd3bcc69d Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:52:44 +0530 Subject: [PATCH 57/81] fix(protocol): a fast-link miss long ago is not one in a row with a miss now --- crates/offline-protocol/src/fast_link.rs | 91 +++++++++++++++++++----- docs/state-machines/fast-link.md | 4 +- 2 files changed, 78 insertions(+), 17 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 567d06956..b4a55bcf7 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -551,7 +551,7 @@ pub(crate) struct FastLinks { ended_joins: VecDeque<(String, String)>, /// Per peer, the links hosted in a row for its requests that expired /// with no stream from it. - unanswered: VecDeque<(String, u8)>, + unanswered: VecDeque<(String, u8, Instant)>, /// Peers whose requests are refused, and since when ([`HOST_BACKOFF`]). host_backoff: VecDeque<(String, Instant)>, /// Per peer, the offers it made without being asked that ended in a row @@ -560,7 +560,7 @@ pub(crate) struct FastLinks { /// Cancel does: a user who ignored the prompt, or a host that never /// proved a stream, otherwise left the peer free to prompt again once /// per offer lifetime. - unanswered_offers: VecDeque<(String, u8)>, + unanswered_offers: VecDeque<(String, u8, Instant)>, /// Peers whose link ended after it was up. A transfer pinned to the /// slot for one of them can no longer reach it: its carrier is fixed when /// it starts, so it would retry on a dead slot until its retries ran out. @@ -594,9 +594,10 @@ impl FastLinks { // The user asking is the user's answer to an earlier decline, and to // the peer's unanswered requests. self.declined.retain(|(declined, _)| declined != peer); - self.unanswered.retain(|(unanswered, _)| unanswered != peer); + self.unanswered + .retain(|(unanswered, _, _)| unanswered != peer); self.unanswered_offers - .retain(|(unanswered, _)| unanswered != peer); + .retain(|(unanswered, _, _)| unanswered != peer); self.host_backoff .retain(|(backed_off, _)| backed_off != peer); if self.roles.can_host { @@ -1077,7 +1078,8 @@ impl FastLinks { now: Instant, ) { if used { - self.unanswered.retain(|(unanswered, _)| unanswered != peer); + self.unanswered + .retain(|(unanswered, _, _)| unanswered != peer); return; } // This device's own ends that still name the peer's silence count: @@ -1090,21 +1092,29 @@ impl FastLinks { { return; } - let count = match self.unanswered.iter_mut().find(|(p, _)| p == peer) { - Some((_, count)) => { - *count = count.saturating_add(1); + // A miss older than the pause it would start is forgotten, so one + // long ago and one now are not two in a row. + let count = match self.unanswered.iter_mut().find(|(p, _, _)| p == peer) { + Some((_, count, at)) => { + *count = if now.saturating_duration_since(*at) >= HOST_BACKOFF { + 1 + } else { + count.saturating_add(1) + }; + *at = now; *count } None => { if self.unanswered.len() >= MAX_ENDED_REMEMBERED { self.unanswered.pop_front(); } - self.unanswered.push_back((peer.to_string(), 1)); + self.unanswered.push_back((peer.to_string(), 1, now)); 1 } }; if count >= MAX_UNANSWERED_HOSTINGS { - self.unanswered.retain(|(unanswered, _)| unanswered != peer); + self.unanswered + .retain(|(unanswered, _, _)| unanswered != peer); if self.host_backoff.len() >= MAX_ENDED_REMEMBERED { self.host_backoff.pop_front(); } @@ -1129,7 +1139,7 @@ impl FastLinks { ) { if used { self.unanswered_offers - .retain(|(unanswered, _)| unanswered != peer); + .retain(|(unanswered, _, _)| unanswered != peer); return; } // Only this device's own ends are skipped. A host never has cause to @@ -1143,22 +1153,33 @@ impl FastLinks { { return; } - let count = match self.unanswered_offers.iter_mut().find(|(p, _)| p == peer) { - Some((_, count)) => { - *count = count.saturating_add(1); + // A miss older than the pause it would start is forgotten, so one + // long ago and one now are not two in a row. + let count = match self + .unanswered_offers + .iter_mut() + .find(|(p, _, _)| p == peer) + { + Some((_, count, at)) => { + *count = if now.saturating_duration_since(*at) >= HOST_BACKOFF { + 1 + } else { + count.saturating_add(1) + }; + *at = now; *count } None => { if self.unanswered_offers.len() >= MAX_ENDED_REMEMBERED { self.unanswered_offers.pop_front(); } - self.unanswered_offers.push_back((peer.to_string(), 1)); + self.unanswered_offers.push_back((peer.to_string(), 1, now)); 1 } }; if count >= MAX_UNANSWERED_HOSTINGS { self.unanswered_offers - .retain(|(unanswered, _)| unanswered != peer); + .retain(|(unanswered, _, _)| unanswered != peer); self.record_decline(peer.to_string(), now); } } @@ -2629,6 +2650,44 @@ mod tests { ); } + #[test] + fn a_miss_long_ago_is_not_one_in_a_row() { + let mut android = machine(host_roles()); + let t0 = Instant::now(); + let mut miss = |android: &mut FastLinks, seed, now: Instant| { + let id = fresh(seed).link_id; + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(seed + 10), + now, + 0, + ); + let hosted = + android.next_directive(now).map(|d| d.kind) == Some(FastLinkDirectiveKind::Host); + if hosted { + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + android.tick(now + OFFER_TTL, |_| false); + android.take_frames(); + android.next_directive(now + OFFER_TTL); + } + hosted + }; + assert!(miss(&mut android, 1, t0)); + // The second miss comes after the pause would have ended: forgiven. + let later = t0 + OFFER_TTL + HOST_BACKOFF; + assert!(miss(&mut android, 2, later)); + assert!( + miss(&mut android, 3, later + OFFER_TTL), + "one miss, not two" + ); + assert!( + !miss(&mut android, 4, later + OFFER_TTL * 2), + "two in a row" + ); + } + #[test] fn a_peer_that_asked_cannot_then_offer_around_the_limits() { let t0 = Instant::now(); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index a2567fd7a..ed571cbfd 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -88,7 +88,9 @@ reason it gives: then it answers `busy` for ten minutes, so a peer cannot keep a group on the air, and the device's own group formation locked out, by asking again each time. A link that came up counts the same as one never joined unless it carried something: otherwise a peer could join, carry -nothing, let the link idle out and ask again, without end. One miss +nothing, let the link idle out and ask again, without end. A miss more than +ten minutes before the next is forgotten, so two in a row means two close +together. One miss is forgiven, so a user who did not tap in time can ask again, and this device's own request to the peer ends the pause. From 793caaf3a3772dfa46172382d590d5580cba0543 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 10:54:16 +0530 Subject: [PATCH 58/81] fix(protocol): a resent fast-link offer carries only the lifetime it has left --- crates/offline-protocol/src/fast_link.rs | 27 +++++++++++++++++++++++- docs/state-machines/fast-link.md | 3 ++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index b4a55bcf7..3002455e1 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -776,7 +776,14 @@ impl FastLinks { } match (link.role, link.state, link.offer) { // The request means our offer was lost: send it again. - (FastLinkRole::Host, FastLinkState::Offered, Some(offer)) => { + (FastLinkRole::Host, FastLinkState::Offered, Some(mut offer)) => { + // With the lifetime the host has left: the joiner counts + // it from arrival, and a resent offer's full lifetime + // kept a joiner, and an iPhone's prompt, on a network + // already gone. + if let Some(deadline) = link.deadline { + offer.ttl_ms = deadline.saturating_duration_since(now).as_millis() as u64; + } let frame = Frame::new(&link.id, FrameBody::Offer(offer)); self.frames.push_back((peer.to_string(), frame)); } @@ -1876,6 +1883,24 @@ mod tests { ); let second = android.take_frames(); assert_eq!(first, second); + // Later, it carries only the lifetime the host has left. + let later = t0 + Duration::from_secs(100); + android.on_frame( + HIGH, + LOW, + Frame::new(&id, FrameBody::Request), + fresh(4), + later, + 0, + ); + let third = android.take_frames(); + let FrameBody::Offer(resent) = &third[0].1.body else { + panic!("an offer"); + }; + assert_eq!( + resent.ttl_ms, + (OFFER_TTL - Duration::from_secs(100)).as_millis() as u64 + ); assert_eq!( android.next_directive(t0).unwrap().kind, FastLinkDirectiveKind::Host diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index ed571cbfd..48e05a14c 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -80,7 +80,8 @@ for go ahead and no join prompt or group appears that it did not want. **A `request` arrives.** A device that cannot host answers `close` (`cannot_host`); one holding a link with another peer answers `close` (`busy`). One that already offered this peer a link sends the same offer again, since -the request means the first one was lost. Otherwise it starts hosting under +the request means the first one was lost, with only the lifetime it has left: +the joiner counts an offer's lifetime from its arrival. Otherwise it starts hosting under the request's link id, unless two links it hosted in a row for that peer's requests carried nothing (no body of 16 KiB or more, no transfer) and ended by expiring, going idle, losing their stream, or at the peer's hand, whatever From 64f3bedd17745b092f0e5560e994cd3e2f3be3d5 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:10:46 +0530 Subject: [PATCH 59/81] fix(protocol): a fast-link offer must name a wi-fi direct group --- crates/offline-protocol/src/fast_link.rs | 20 +++++++++++++++++++- docs/spec/control-messages.md | 5 ++++- docs/state-machines/fast-link.md | 3 ++- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 3002455e1..a70c4fdbc 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -321,7 +321,12 @@ impl Offer { /// The bounds of the control-messages chapter, against the receiver's /// clock. pub(crate) fn is_valid(&self, now_ms: i64) -> bool { - let ssid_ok = (1..=32).contains(&self.ssid.len()); + // A Wi-Fi Direct group's name, as every host's is (Android refuses + // any other). Any name let a peer offer the network the joiner was + // already on: an iPhone took the join as done and dialled the offer's + // address on the user's own network. + let ssid_ok = (SSID_PREFIX.len() + 2..=32).contains(&self.ssid.len()) + && self.ssid.starts_with(SSID_PREFIX); let passphrase_ok = (8..=63).contains(&self.passphrase.len()) && self.passphrase.bytes().all(|b| (0x20..=0x7e).contains(&b)); let ttl_ok = self.ttl_ms > 0 && self.ttl_ms <= MAX_OFFER_TTL_MS; @@ -333,6 +338,10 @@ impl Offer { } } +/// What every offered network's name starts with, and two characters after +/// it: a Wi-Fi Direct group's. +pub const SSID_PREFIX: &str = "DIRECT-"; + /// A link id and credentials, drawn by the engine from its random source. #[derive(Clone, PartialEq, Eq)] pub struct FreshLink { @@ -1622,6 +1631,15 @@ mod tests { ssid: String::new(), ..good.clone() }, + // The network the joiner may already be on: never a group. + Offer { + ssid: "HomeWiFi".to_string(), + ..good.clone() + }, + Offer { + ssid: "DIRECT-".to_string(), + ..good.clone() + }, Offer { port: 0, ..good.clone() diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index 6ed1a4421..8645e2d3e 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -501,7 +501,10 @@ Four rules hold for every frame of the family: custodian. - **Gated by `link_versions` entry 1.** No frame of the family is sent to a peer that has not advertised it ([Capability negotiation](capability-negotiation.md)). -- **Bounded.** A receiver refuses an offer whose `ssid` is not 1 to 32 bytes, +- **Bounded.** A receiver refuses an offer whose `ssid` is not 9 to 32 bytes + starting `DIRECT-` (a Wi-Fi Direct group's name, as every host's is; any + name let a peer offer the network the joiner was already on, and an iPhone + took that join as done and dialled the offer's address there), whose `passphrase` is not 8 to 63 printable ASCII characters, whose `host` is not an IP literal in a private or link-local range, whose `port` is 0, whose `ttl_ms` is over 300,000, or whose `issued_at_ms` lies more than 300 s ahead diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 48e05a14c..cfaaeeb49 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -143,7 +143,8 @@ asked again, so the prompt is wanted, and the offer answers the new request. A host still offering the old network sends it again for the new request, and refusing it ended the user's second attempt `no_offer` with nothing shown. -An offer is valid when its name is 1 to 32 bytes, its passphrase 8 to 63 +An offer is valid when its name is 9 to 32 bytes starting `DIRECT-`, as a +Wi-Fi Direct group's is, its passphrase 8 to 63 printable ASCII characters, its host a private or link-local IP literal, its port not zero, its lifetime at most 300 s, and the time it states it was made no more than 300 s in the future or more than its lifetime plus 300 s in the From 6cb56fe900392437a31c0d251d7b33d2dec2d876 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:10:46 +0530 Subject: [PATCH 60/81] fix(bindings): an iphone never dials an offer naming the network it is already on --- .../react-native/ios/WifiDirectManager.swift | 19 ++++++++++++++++--- docs/security/threat-model.md | 4 +++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 002884afe..0a354fae5 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -910,8 +910,8 @@ extension WifiDirectManager { /// Whether `error` is the hotspot error `code`. The domain is checked: /// another framework's error that shares the number would otherwise read - /// as the user's refusal, starting the peer's decline pause, or as a join - /// that held. + /// as the user's refusal, starting the peer's decline pause, or as an + /// offer that named the network the phone is already on. private static func isHotspotError( _ error: NSError?, _ code: NEHotspotConfigurationError ) -> Bool { @@ -979,7 +979,20 @@ extension WifiDirectManager { } return } - if let error = error, !Self.isHotspotError(error, .alreadyAssociated) { + if Self.isHotspotError(error, .alreadyAssociated) { + // A fast link's network is new and its name random, so a phone + // already on it was never on a fast link: the peer named the + // network the phone was on, and a dial would go to the offer's + // address on the user's own network. Nothing was configured, so + // nothing is removed; the user's network stays as it was. + emitDiagnostic("warning", "Fast link: the offer named the network the phone is already on", context: [ + "linkId": link.linkId, + ]) + fastLink = nil + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "invalid") + return + } + if let error = error { let reason = Self.isHotspotError(error, .userDenied) ? "declined" : "failed" emitDiagnostic("warning", "Fast link: the join did not happen", context: [ "linkId": link.linkId, diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index d09402673..dd898f555 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1480,7 +1480,9 @@ and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial stays on the group (an iPhone dials only once iOS reports it is on the offered network, since a join can finish with no error while the phone stays -on its own Wi-Fi; an Android, which keeps its own Wi-Fi, dials the group +on its own Wi-Fi; the offered name must be a Wi-Fi Direct group's, and an +offer naming the network the iPhone is already on, which iOS reports as +already joined, ends `invalid` and is never dialled; an Android, which keeps its own Wi-Fi, dials the group owner's address and not the offer's), and the stream must prove the offerer's own address, so a link that proves nothing ends when its offer expires, at most From c5da4b9856230abbcd7e36af0e7d4de0bf1786e3 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:11:55 +0530 Subject: [PATCH 61/81] fix(bindings): stopping the transport ends a fast link as closed, never against the peer --- .../java/com/offlineprotocol/WifiDirectManager.kt | 12 ++++++++---- bindings/react-native/ios/WifiDirectManager.swift | 3 ++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 05ae9f268..6d254941f 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1771,7 +1771,11 @@ class WifiDirectManager( } } - /** The transport is stopping: anything held for a link goes with it. */ + /** + * The transport is stopping: anything held for a link goes with it, + * reported `closed`, this device's own end, which never counts against + * the peer the way a failure might. + */ @SuppressLint("MissingPermission") private fun endFastLinkOnStop() { val hosted = fastLinkHosted @@ -1782,13 +1786,13 @@ class WifiDirectManager( parkedFastLinkJoin = null fastLinkLeaving = false orphanedFastLinkSsid = null - parked?.let { fastLinkEnded(it.linkId, "failed") } + parked?.let { fastLinkEnded(it.linkId, "closed") } val ch = channel if ((hosted != null || joined != null) && ch != null) { wifiP2pManager?.removeGroup(ch, quietListener("end fast link on stop")) } - hosted?.let { fastLinkEnded(it.linkId, "failed") } - joined?.let { fastLinkEnded(it.linkId, "failed") } + hosted?.let { fastLinkEnded(it.linkId, "closed") } + joined?.let { fastLinkEnded(it.linkId, "closed") } try { protocol.wifiDirectSetFastLinkRoles(false, false, false) } catch (_: Exception) {} diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 0a354fae5..9a90bd128 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -344,7 +344,8 @@ public class WifiDirectManager: NSObject, TransportManager { try? protocolInstance.wifiDirectStatusChanged(isConnected: false) try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false, acceptUnrequested: false) - onLinkQueueSync { endFastLink(reason: "failed") } + // This device's own end, which never counts against the peer. + onLinkQueueSync { endFastLink(reason: "closed") } updateState(.stopped) emitDiagnostic("info", "Peer-stream transport stopped") From 63461910d49f19f52b37e3c9c8cf8d0a9a9a1212 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:11:55 +0530 Subject: [PATCH 62/81] docs: name the fast-link residual of a peer that uses every link --- docs/security/threat-model.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index dd898f555..5037c39bd 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1513,7 +1513,11 @@ nothing, each an offer lifetime and, if joined, the idle limit after it (about six minutes in all), before the host stops answering that peer's requests for ten minutes. A link that came up counts toward this unless it carried a body of 16 KiB or a transfer, so joining and idling does not reset -it. +it. A peer that does use each link, sending that much over it every time, +can ask again and again: the device then serves links a session peer is +really using, each ended by the idle limit a minute after the last of it, and +the user's own way out is to block that peer or set `wifiDirect.fastLink` to +`requestedOnly`. **Why it stands:** a network that does not broadcast its existence cannot be joined by an iPhone that was handed its name, and the session is the only From 0013b58eb26b52b7d6e50c3180bd448d79937a9e Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:28:06 +0530 Subject: [PATCH 63/81] fix(protocol): only an offer naming the waiting request answers it after its link was given up --- crates/offline-protocol/src/fast_link.rs | 99 ++++++++++++++++++++++-- docs/spec/control-messages.md | 5 +- docs/state-machines/fast-link.md | 19 +++-- 3 files changed, 108 insertions(+), 15 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index a70c4fdbc..cf1d132fd 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -255,6 +255,12 @@ pub(crate) struct Offer { pub(crate) port: u16, pub(crate) issued_at_ms: i64, pub(crate) ttl_ms: u64, + /// The request this offer answers when it is sent again for a request + /// under another id (a retry after a lost offer). Only such an offer + /// may answer a request after its own link id was given up; any other + /// late offer names a network that may already be gone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) re: Option, } impl fmt::Debug for Offer { @@ -267,6 +273,7 @@ impl fmt::Debug for Offer { .field("port", &self.port) .field("issued_at_ms", &self.issued_at_ms) .field("ttl_ms", &self.ttl_ms) + .field("re", &self.re) .finish() } } @@ -334,7 +341,8 @@ impl Offer { let oldest = now_ms - self.ttl_ms as i64 - OFFER_CLOCK_SLACK_MS; let newest = now_ms + OFFER_CLOCK_SLACK_MS; let time_ok = ttl_ok && (oldest..=newest).contains(&self.issued_at_ms); - ssid_ok && passphrase_ok && is_local_host(&self.host) && self.port != 0 && time_ok + let re_ok = self.re.as_deref().is_none_or(is_link_id); + ssid_ok && passphrase_ok && is_local_host(&self.host) && self.port != 0 && time_ok && re_ok } } @@ -705,6 +713,7 @@ impl FastLinks { port, issued_at_ms: now_ms, ttl_ms: OFFER_TTL.as_millis() as u64, + re: None, }; link.state = FastLinkState::Offered; link.deadline = Some(now + OFFER_TTL); @@ -732,12 +741,15 @@ impl FastLinks { // wanted, and a host still holding the old network answers the new // request with it. Refused, the retry after a lost offer met a host // that resent the old one, and ended `no_offer` with nothing shown. - let answers_request = matches!(frame.body, FrameBody::Offer(_)) - && self.link.as_ref().is_some_and(|link| { + let answers_request = match &frame.body { + FrameBody::Offer(offer) => self.link.as_ref().is_some_and(|link| { link.peer == peer && link.role == FastLinkRole::Join && link.state == FastLinkState::Requested - }); + && offer.re.as_deref() == Some(link.id.as_str()) + }), + _ => false, + }; if !answers_request && self.ended_recently(&frame.link, now) { // A late request needs no answer: its sender has given up on it. // A late offer gets one, so the host takes its network down. @@ -793,6 +805,11 @@ impl FastLinks { if let Some(deadline) = link.deadline { offer.ttl_ms = deadline.saturating_duration_since(now).as_millis() as u64; } + // Naming the request it answers when that request has an + // id of its own: the requester gave the offer's id up, + // and takes this offer only because it names the request + // still waiting. + offer.re = (link.id != link_id).then(|| link_id.to_string()); let frame = Frame::new(&link.id, FrameBody::Offer(offer)); self.frames.push_back((peer.to_string(), frame)); } @@ -1612,6 +1629,7 @@ mod tests { port: 8988, issued_at_ms: 1_000_000, ttl_ms: 120_000, + re: None, }; assert!(good.is_valid(1_000_000)); let bad = [ @@ -1704,6 +1722,28 @@ mod tests { Frame::parse(&format!("{{\"v\":1,\"link\":\"{id}\",\"kind\":\"dance\"}}")).is_none() ); assert!(Frame::parse(&" ".repeat(MAX_FRAME_BODY_BYTES + 1)).is_none()); + // An offer's `re` is left out when it names nothing, so an offer + // reads the same to a receiver from before it. + let offer = Offer { + ssid: "DIRECT-ab-0123456789ab".to_string(), + passphrase: "b".repeat(32), + host: "192.168.49.1".to_string(), + port: 8988, + issued_at_ms: 0, + ttl_ms: 120_000, + re: None, + }; + let plain = Frame::new(&id, FrameBody::Offer(offer.clone())); + assert!(!plain.encode().contains("\"re\"")); + assert_eq!(Frame::parse(&plain.encode()), Some(plain)); + let resent = Frame::new( + &id, + FrameBody::Offer(Offer { + re: Some(fresh(2).link_id), + ..offer + }), + ); + assert_eq!(Frame::parse(&resent.encode()), Some(resent)); // A later field is ignored, not refused. let later = wire.replacen('{', "{\"later\":true,", 1); assert!(Frame::parse(&later).is_some()); @@ -1787,6 +1827,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; iphone.on_frame( LOW, @@ -1978,6 +2019,43 @@ mod tests { assert_eq!(states(&mut iphone), [FastLinkState::Closed]); } + #[test] + fn a_late_offer_for_a_removed_network_never_answers_a_new_request() { + let t0 = Instant::now(); + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let first = iphone.request(LOW, fresh(1), t0).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, t0, 0); + android.next_directive(t0); + assert!(android.hosting(&first, "192.168.49.1", 8988, t0, 0)); + // The offer is delayed; the requester gives up and its close reaches + // the host, which takes that network down. + let late_offer = android.take_frames(); + let gave_up = t0 + REQUEST_TIMEOUT; + iphone.tick(gave_up, |_| false); + deliver(&mut iphone, HIGH, &mut android, LOW, gave_up, 0); + assert!(android.peer().is_none()); + android.next_directive(gave_up); + + // The user asks again, and the host brings up a second network. + let second = iphone.request(LOW, fresh(2), gave_up).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, gave_up, 0); + android.next_directive(gave_up); + assert!(android.hosting(&second, "192.168.49.1", 8988, gave_up, 0)); + + // The first network's offer lands now: refused, never prompted. + for (_, frame) in late_offer { + iphone.on_frame(LOW, HIGH, frame, fresh(3), gave_up, 0); + } + assert!(!iphone.has_directives(), "a prompt for a removed network"); + iphone.take_frames(); + // The second network's offer is the one joined. + deliver(&mut android, LOW, &mut iphone, HIGH, gave_up, 0); + let join = iphone.next_directive(gave_up).unwrap(); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert_eq!(join.link_id, second); + } + #[test] fn a_late_offer_for_a_link_given_up_on_is_refused_not_joined() { let t0 = Instant::now(); @@ -2081,6 +2159,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; iphone.on_frame( LOW, @@ -2112,6 +2191,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; links.on_frame( LOW, @@ -2193,6 +2273,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; iphone.on_frame( LOW, @@ -2215,6 +2296,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; let mut iphone = machine(join_roles()); let first = fresh(1).link_id; @@ -2273,6 +2355,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; let mut iphone = machine(join_roles()); let first = fresh(1).link_id; @@ -2433,6 +2516,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; let theirs = fresh(2).link_id; iphone.on_frame( @@ -2499,6 +2583,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; iphone.on_frame( LOW, @@ -2649,7 +2734,7 @@ mod tests { let mut now = Instant::now(); // The peer asks, joins, proves its stream, carries nothing, and lets // the link idle out; then asks again. - let mut round = |android: &mut FastLinks, seed, now: Instant, carry: bool| { + let round = |android: &mut FastLinks, seed, now: Instant, carry: bool| { let id = fresh(seed).link_id; android.on_frame( HIGH, @@ -2697,7 +2782,7 @@ mod tests { fn a_miss_long_ago_is_not_one_in_a_row() { let mut android = machine(host_roles()); let t0 = Instant::now(); - let mut miss = |android: &mut FastLinks, seed, now: Instant| { + let miss = |android: &mut FastLinks, seed, now: Instant| { let id = fresh(seed).link_id; android.on_frame( HIGH, @@ -2744,6 +2829,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; let id = fresh(1).link_id; high.on_frame( @@ -2806,6 +2892,7 @@ mod tests { port: 8988, issued_at_ms: 0, ttl_ms: 120_000, + re: None, }; let other = fresh(2).link_id; high.on_frame( diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index 8645e2d3e..33ed9a97e 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -482,7 +482,7 @@ random: | `kind` | Further fields | Meaning | |--------|----------------|---------| | `request` | none | The sender can join a network and asks the recipient to host one | -| `offer` | `ssid`, `passphrase`, `host`, `port`, `issued_at_ms`, `ttl_ms` | The sender is hosting a network for the recipient: join `ssid` with `passphrase` and dial `host:port`, within `ttl_ms` of arrival | +| `offer` | `ssid`, `passphrase`, `host`, `port`, `issued_at_ms`, `ttl_ms`, and `re` when it is sent again for a request under another id | The sender is hosting a network for the recipient: join `ssid` with `passphrase` and dial `host:port`, within `ttl_ms` of arrival. `re` names the request it answers; left out otherwise | | `close` | `reason` | The link with this id is over | Four rules hold for every frame of the family: @@ -509,7 +509,8 @@ Four rules hold for every frame of the family: not an IP literal in a private or link-local range, whose `port` is 0, whose `ttl_ms` is over 300,000, or whose `issued_at_ms` lies more than 300 s ahead of its clock or more than `ttl_ms` plus 300 s behind it, and answers it with - a `close` whose `reason` is `invalid`. A `host` is never resolved as a name. + a `close` whose `reason` is `invalid`, as it does one whose `re` is present + and not a link id. A `host` is never resolved as a name. `reason` is one of `declined`, `failed`, `host_failed`, `cannot_host`, `cannot_join`, `busy`, `invalid`, `expired`, `no_offer`, `lost`, `idle`, diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index cfaaeeb49..d6171f1b4 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -80,8 +80,9 @@ for go ahead and no join prompt or group appears that it did not want. **A `request` arrives.** A device that cannot host answers `close` (`cannot_host`); one holding a link with another peer answers `close` (`busy`). One that already offered this peer a link sends the same offer again, since -the request means the first one was lost, with only the lifetime it has left: -the joiner counts an offer's lifetime from its arrival. Otherwise it starts hosting under +the request means the first one was lost, with only the lifetime it has left +(the joiner counts an offer's lifetime from its arrival) and, when the +request has an id of its own, naming that request in `re`. Otherwise it starts hosting under the request's link id, unless two links it hosted in a row for that peer's requests carried nothing (no body of 16 KiB or more, no transfer) and ended by expiring, going idle, losing their stream, or at the peer's hand, whatever @@ -137,11 +138,15 @@ request is dropped; an offer is answered `close` (`expired`), so the host takes its network down, and is never joined. On two phones a request delayed 63 s reached the host after the requester had given up, and before this rule its offer prompted the requester's user to join a network that had -already been removed. The one exception is an offer from a peer this device -is waiting on now, its own request to that peer still open: the user has just -asked again, so the prompt is wanted, and the offer answers the new request. -A host still offering the old network sends it again for the new request, and -refusing it ended the user's second attempt `no_offer` with nothing shown. +already been removed. The one exception is an offer that names, in its +`re`, the request this device is waiting on now: a host still offering the +old network sends it again for a request under a new id (the requester's +`close` for the old one was lost too), and refusing it ended the user's +second attempt `no_offer` with nothing shown. An offer that is merely late, +however much the user has asked again since, is refused as above: let +through, it prompted for a network the host had already removed, and the +second network's offer, then refused as late, started the host's backoff +against a user who had only asked twice. An offer is valid when its name is 9 to 32 bytes starting `DIRECT-`, as a Wi-Fi Direct group's is, its passphrase 8 to 63 From 62d454bcfd9fbb869d4e308166ba0c2623b1a40c Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:28:31 +0530 Subject: [PATCH 64/81] docs(bindings): the android group builder's guard no longer says the engine takes any name --- .../src/main/java/com/offlineprotocol/WifiDirectManager.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 6d254941f..208353f0b 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -2297,9 +2297,10 @@ internal object WifiDirectFormationProgress { * The Wi-Fi Direct group a fast link names (ADR 0038), or null where Android * cannot make one: below Android 10, or for a name or passphrase it refuses. * `WifiP2pConfig.Builder` throws for a name that does not start `DIRECT-` and - * two characters, which the engine allows (an iPhone joins any name), so an - * offer from another implementation must never reach the builder unguarded: - * on the transport looper the throw is a crash. + * two characters, and for other names and passphrases it will not take. The + * engine refuses an offer without the prefix, but the builder's rules are + * Android's and may be stricter than the engine's, so nothing reaches it + * unguarded: on the transport looper the throw is a crash. */ internal object FastLinkGroupConfig { fun build(ssid: String, passphrase: String): WifiP2pConfig? { From 39cd247966af0e74b99676a9666b1e88fd1725af Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:28:59 +0530 Subject: [PATCH 65/81] docs: say how an iphone's fast link ends on leaving the foreground, paused or not --- .../0038-a-fast-link-is-offered-inside-the-session.md | 10 +++++++--- docs/state-machines/fast-link.md | 9 ++++++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 3f4c16e7e..488b471c8 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -102,9 +102,13 @@ the foreground and deleted the passphrase. proved stream is lost, after 60 s with nothing large carried (a body of 16 KiB or more) and no transfer to the peer under way, on either side's `close`, and on the application's `close_fast_link`. A joiner's platform reports its own end when it can no - longer hold the network: iOS does when the application leaves the - foreground, because iOS disconnects 15 s later anyway and the host would - otherwise hold a dead stream until keepalive notices, measured at 40 s. + longer hold the network: iOS does when the application pauses the engine + on leaving the foreground, because iOS disconnects 15 s later anyway and + the host would otherwise hold a dead stream until keepalive notices, + measured at 40 s. An application that does not pause still loses the + link: its transport reports itself down on leaving the foreground, which + ends an up link `lost`, and a join still in progress ends when its offer + expires. Bluetooth stays up throughout and carries the traffic before, during the switch and after. diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index d6171f1b4..cc05fda7a 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -198,9 +198,12 @@ it as an ordinary group, which left it up with no timer and refused every later link. A joiner's platform that is about to lose the network reports it as `ended` -first: on iOS, leaving the foreground, after which iOS disconnects at 15 s -whatever the engine thinks. Without the report the host learns from TCP -keepalive, about 40 s later. +first: on iOS, when the application pauses the engine on leaving the +foreground, after which iOS disconnects at 15 s whatever the engine thinks. +Without the report the host learns from TCP keepalive, about 40 s later. An +application that leaves the foreground without pausing still ends the link: +its transport reports itself down, which ends an up link `lost`, and a join +still in progress ends `expired` at its offer's lifetime. ## Events From 9d2627ef9286b2e20dafc9afd7862e177b0f3b4e Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:38:33 +0530 Subject: [PATCH 66/81] fix(protocol): a close for a fast link is never refused as late --- crates/offline-protocol/src/fast_link.rs | 18 +++++++++++++++++- docs/state-machines/fast-link.md | 7 +++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index cf1d132fd..8b21e28ca 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -750,7 +750,12 @@ impl FastLinks { }), _ => false, }; - if !answers_request && self.ended_recently(&frame.link, now) { + // A close is never late: it acts only on the link held under its id, + // and gated here it was dropped for a link adopted through `re`, + // whose id this device had ended once, so the host's close never + // stopped the join. + let is_close = matches!(frame.body, FrameBody::Close { .. }); + if !is_close && !answers_request && self.ended_recently(&frame.link, now) { // A late request needs no answer: its sender has given up on it. // A late offer gets one, so the host takes its network down. if matches!(frame.body, FrameBody::Offer(_)) { @@ -1996,6 +2001,17 @@ mod tests { iphone.stream_proved(LOW, later); android.stream_proved(HIGH, later); assert_eq!(states(&mut android).last(), Some(&FastLinkState::Up)); + + // The host's close ends it, although its id was given up once. + iphone.take_changes(); + assert!(android.close(HIGH, later)); + deliver(&mut android, LOW, &mut iphone, HIGH, later, 0); + assert!(iphone.peer().is_none()); + assert_eq!(states(&mut iphone), [FastLinkState::Closed]); + assert_eq!( + iphone.next_directive(later).unwrap().kind, + FastLinkDirectiveKind::Close + ); } #[test] diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index cc05fda7a..5217e0094 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -132,8 +132,11 @@ on unasked offers. **A `close` arrives.** It ends the link with that id, if there is one, and is never answered. -**A frame arrives for a link this device ended** within the last ten -minutes (the longest an offer lives, plus the clock slack). It is late. A +**A request or offer arrives for a link this device ended** within the last +ten minutes (the longest an offer lives, plus the clock slack). It is late. A +`close` never is: it ends only the link held under its id, and treated as +late it was dropped for a link adopted through `re` (below), whose id this +device had ended once, so the host's close never stopped the join. A request is dropped; an offer is answered `close` (`expired`), so the host takes its network down, and is never joined. On two phones a request delayed 63 s reached the host after the requester had given up, and before From 23b73e85fe77e69b4628d52fcda040a800880af1 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:38:33 +0530 Subject: [PATCH 67/81] docs(uniffi): list every reason a platform reports a fast link ended with --- .../csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs | 2 +- .../src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs | 2 +- .../src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part01.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part02.g.cs | 2 +- .../Generated/ProtocolEngine.LocalApi.part03.g.cs | 2 +- .../Generated/ProtocolEngine.Static.g.cs | 2 +- bindings/python/offline_protocol_sdk/local_api/table.py | 2 +- crates/offline-protocol-uniffi/src/offline_protocol.udl | 7 +++++-- 9 files changed, 13 insertions(+), 10 deletions(-) diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index faeed711d..ffc8de061 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index 448e84882..ffa10bca2 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index 84f34765b..84bb98c5b 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index 3aeaf279f..6738f7b28 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index 810c74a3d..f53a70dae 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 62158b776..3608dc518 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index e20a60a69..560ff281e 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28 +// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc // Do not edit. #nullable enable diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index fbda42581..896975fa4 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "b23e810b2692e9536c0154d6a991910ead826c5fd7f0d2ab8527116442348f28" +UDL_SHA256 = "a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index 14d487f8e..86f6ec543 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1513,8 +1513,11 @@ interface OfflineProtocol { // The platform could not do what it was told, or can no longer hold the // link: `declined` (the user refused the join), `failed`, `host_failed`, - // or `background` (iOS drops a joined network 15 s after the app leaves - // the foreground). The peer is told. + // `background` (iOS drops a joined network 15 s after the app leaves + // the foreground), `lost` (the network went away), `invalid` (the offer + // named a network the device is already on) or `closed` (the platform + // stopped). Any other token reads as `failed`; the full list is the + // `close` reasons in docs/spec/control-messages.md. The peer is told. void wifi_direct_fast_link_ended(string link_id, string reason); // Reticulum transport callback (event-driven sending) From 2cf4ae7abb19e5db17745791ea06350b7a804dc0 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 11:39:59 +0530 Subject: [PATCH 68/81] test(uniffi): no bridge logs a fast-link directive whole --- crates/offline-protocol-uniffi/src/lib.rs | 51 +++++++++++++++++++++++ docs/bridges/README.md | 7 +++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 5c1023e4a..ec0b326b1 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20236,6 +20236,57 @@ mod tests { } } + /// No bridge manager logs a fast-link directive whole (invariant 5 of + /// `docs/state-machines/fast-link.md`). The generated records are a Kotlin + /// data class and a Swift struct whose `toString` and description print + /// every field, the passphrase among them; only the Rust `Debug` is + /// redacted. Each value is named, the link id and the kind, never the + /// record. + #[test] + fn no_bridge_logs_a_fast_link_directive_whole() { + let kotlin = + rn_source_code_only("android/src/main/java/com/offlineprotocol/WifiDirectManager.kt"); + let swift = rn_source_code_only("ios/WifiDirectManager.swift"); + for name in ["directive", "parked", "parkedFastLinkJoin"] { + for (bridge, code, forms) in [ + ( + "WifiDirectManager.kt", + &kotlin, + vec![ + format!("${name}\""), + format!("${name} "), + format!("${name}."), + format!("${{{name}}}"), + format!("{name}.toString()"), + format!("to {name})"), + format!("to {name},"), + ], + ), + ( + "WifiDirectManager.swift", + &swift, + vec![ + format!("\\({name})"), + format!("String(describing: {name}"), + format!(": {name}]"), + format!(": {name},"), + format!("print({name}"), + format!("dump({name}"), + ], + ), + ] { + for form in forms { + assert!( + !code.contains(&form), + "{bridge} logs or stringifies a whole fast-link directive ({form:?}): \ + its generated description prints the passphrase. Name the link id \ + and kind instead." + ); + } + } + } + } + /// The fast-link tokens the bridges hand the engine, and the directive /// kinds they branch on, are the engine's own (C5). Both cross the FFI as /// strings, and the engine reads an unknown reason as `failed` without a diff --git a/docs/bridges/README.md b/docs/bridges/README.md index 71fe35948..e20f858bc 100644 --- a/docs/bridges/README.md +++ b/docs/bridges/README.md @@ -170,7 +170,12 @@ reports through `wifi_direct_fast_link_ended` and the directive kinds it branches on cross the FFI as strings, and the engine reads an unknown reason as `failed`, so a misspelt `declined` silently switches off the decline pause the threat model counts on. `fast_link_tokens_in_the_bridges_are_the_engines` -reads both managers and holds each token to the engine's own. +reads both managers and holds each token to the engine's own. The directive +itself carries the passphrase, and its generated record (a Kotlin data class, +a Swift struct, a Python record) prints every field when stringified, unlike +the redacted Rust `Debug`: `no_bridge_logs_a_fast_link_directive_whole` +refuses a whole directive interpolated or passed to a log in either manager, +so a diagnostic names the link id and kind and never the record. The per-send application id is pinned the same way, by `react_native_rich_sends_carry_the_app_id_end_to_end`. It is optional at every From 27f54b8cb9c99e4d9609a9974210e487689eef02 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 15:10:09 +0530 Subject: [PATCH 69/81] fix(bindings): an iphone's transport stop ends its fast link closed before its streams are lost --- bindings/react-native/ios/WifiDirectManager.swift | 10 +++++++--- crates/offline-protocol-uniffi/src/lib.rs | 10 ++++++++-- docs/state-machines/fast-link.md | 5 ++++- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 9a90bd128..a809d9363 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -332,6 +332,13 @@ public class WifiDirectManager: NSObject, TransportManager { unprovable = [] dialPolicy.reset() + // The fast link ends as this device's own end, which never counts + // against the peer, before any stream is reported lost: after + // endAll() the engine has already seen the link's stream drop and + // ended it `lost`, a miss charged to a peer that offered it. + try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false, acceptUnrequested: false) + endFastLink(reason: "closed") + // Report every proved peer lost while the core still holds its // link, before the layer goes down, on linkQueue so no delivery // lands after a loss report. @@ -343,9 +350,6 @@ public class WifiDirectManager: NSObject, TransportManager { } try? protocolInstance.wifiDirectStatusChanged(isConnected: false) - try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false, acceptUnrequested: false) - // This device's own end, which never counts against the peer. - onLinkQueueSync { endFastLink(reason: "closed") } updateState(.stopped) emitDiagnostic("info", "Peer-stream transport stopped") diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index ec0b326b1..f784f6426 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -21344,7 +21344,10 @@ mod tests { /// queued then finds nothing; forgotten after `endAll()`, a stream that /// became ready in between was announced into the emptied table, and the /// core held a link to a stream that was about to be cancelled. The - /// Multipeer manager this replaced lost a remote exactly that way. + /// Multipeer manager this replaced lost a remote exactly that way. The + /// fast link ends `closed` between the two: after `endAll()` the engine + /// has seen its stream drop and ended it `lost`, which counts as a miss + /// against a peer that offered it unasked. /// /// Android resets the redial delay on a new connection after a /// disconnect (group owners nearly always share one address, so the @@ -21360,9 +21363,12 @@ mod tests { let old = (listener: listener, browser: browser, streams: streams) \ listener = nil browser = nil streams = [] adverts = [:] unprovable = [] \ dialPolicy.reset() \ + try? protocolInstance.wifiDirectSetFastLinkRoles(canHost: false, canJoin: false, acceptUnrequested: false) \ + endFastLink(reason: \"closed\") \ peers.endAll() old.listener?.cancel()" ), - "ios/WifiDirectManager.swift: stop() must forget every stream before endAll()" + "ios/WifiDirectManager.swift: stop() must forget every stream, then end the fast \ + link `closed`, before endAll()" ); let kotlin = rn_source_code_only("android/src/main/java/com/offlineprotocol/WifiDirectManager.kt"); diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 5217e0094..7a9f3974d 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -191,7 +191,10 @@ Pausing the engine ends a link with `background`: a paused engine runs none of these timers, and a host's group would otherwise stay on the air until the application returned, with nothing bounding it. Stopping it ends a link with `closed`, for the same reason and one more: an engine started again would -find the old link still held and answer every request `busy`. +find the old link still held and answer every request `busy`. A platform +whose transport stops reports the link ended `closed` before it reports its +streams lost: reported after, the engine has already seen the link's stream +drop and ended it `lost`, a miss charged to a peer that offered it. A host whose process dies ends nothing: an Android group belongs to the system, not the process, and stays on the air. The host's platform keeps the From a3da02b6f3ff0e6d57d84560834f42b4d991250b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 16:15:30 +0530 Subject: [PATCH 70/81] fix(bindings): an iphone confirms the fast-link network by its gateway, not its name NEHotspotNetwork.fetchCurrent names no joinOnce network without location permission, so on an iphone 16 every join was given up failed five seconds after the phone was on the group. the host's offered address is the group owner, the gateway of the wi-fi path, so the dial now waits for that. the access wi-fi information entitlement and the ios 14 floor are no longer needed. --- CHANGELOG.md | 3 +- .../react-native/ios/WifiDirectManager.swift | 78 +++++++++---------- bindings/react-native/src/index.ts | 5 +- crates/offline-protocol-uniffi/src/lib.rs | 22 ++++++ ...fast-link-is-offered-inside-the-session.md | 16 ++-- docs/mobile-permissions.md | 23 ++---- docs/security/threat-model.md | 8 +- 7 files changed, 84 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afa405d34..392a96d83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,8 +29,7 @@ Questions about a release, or about upgrading to one? Ask in the 2.5 s on two phones. Progress arrives as `fast_link_changed` events; the link ends after 60 s with nothing large to carry, when the iPhone app leaves the foreground, or on `closeFastLink`. An iOS app needs the Hotspot - Configuration and Access Wi-Fi Information entitlements (iOS 14 or later), - and an Android app `NEARBY_WIFI_DEVICES` (fine + Configuration entitlement, and an Android app `NEARBY_WIFI_DEVICES` (fine location below Android 13); see [mobile permissions](docs/mobile-permissions.md#fast-link). `wifiDirect.fastLink` decides how far an app takes part: `any` (the default) also hosts for a peer's request and joins an offer it did not ask diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index a809d9363..bedb983c0 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -14,7 +14,6 @@ import Network // every use of Network's ambiguous in this file. import class NetworkExtension.NEHotspotConfiguration import class NetworkExtension.NEHotspotConfigurationManager -import class NetworkExtension.NEHotspotNetwork import enum NetworkExtension.NEHotspotConfigurationError import let NetworkExtension.NEHotspotConfigurationErrorDomain @@ -298,14 +297,10 @@ public class WifiDirectManager: NSObject, TransportManager { try? protocolInstance.wifiDirectStatusChanged(isConnected: true) emitDiagnostic("info", "Peer-stream transport started") // An iPhone joins a fast link and cannot host one (ADR 0038), as far - // as the application's `wifiDirect.fastLink` allows. Only from iOS - // 14, which can say what network the phone is on: a join is dialed - // only once it is on the offered one (`dialFastLink`). - let canConfirmNetwork: Bool - if #available(iOS 14.0, *) { canConfirmNetwork = true } else { canConfirmNetwork = false } + // as the application's `wifiDirect.fastLink` allows. try? protocolInstance.wifiDirectSetFastLinkRoles( canHost: false, - canJoin: fastLinkMode != .off && canConfirmNetwork, + canJoin: fastLinkMode != .off, acceptUnrequested: fastLinkMode == .any ) } @@ -880,8 +875,6 @@ private final class FastLinkJoin { let deadline: TimeInterval /// iOS reported the join. var joined = false - /// Checks in a row in which iOS named no current network at all. - var networkUnknown = 0 /// The stream dialed toward the host for this link. weak var stream: AnyObject? @@ -905,13 +898,6 @@ private final class FastLinkJoin { extension WifiDirectManager { /// Gives a dial this long to become ready before it is tried again. private static let FAST_LINK_REDIAL: TimeInterval = 2.0 - /// Checks in a row, one per redial, in which iOS names no current - /// network before the join is given up as `failed`. It names none while - /// the phone is on a network this app did not configure, so a join that - /// never happened, and none at all without the Access Wi-Fi Information - /// entitlement; either way the link would otherwise wait out its offer, - /// two minutes, with nothing said. - private static let FAST_LINK_NETWORK_UNKNOWN_LIMIT = 5 /// Whether `error` is the hotspot error `code`. The domain is checked: /// another framework's error that shares the number would otherwise read @@ -1033,31 +1019,41 @@ extension WifiDirectManager { // error while the phone stays on its own Wi-Fi (a wrong passphrase, // a group already gone), and `.wifi` alone would then send the dial, // and the preamble, to whatever the offer named on the user's home - // network. Until the phone is on it, the dial waits; the engine's - // deadline bounds the wait. - guard #available(iOS 14.0, *) else { return } - NEHotspotNetwork.fetchCurrent { [weak self] network in - guard let self = self else { return } - self.linkQueue.async { - guard self.fastLink === link else { return } - guard let network = network else { - link.networkUnknown += 1 - if link.networkUnknown >= Self.FAST_LINK_NETWORK_UNKNOWN_LIMIT { - self.emitDiagnostic("error", "Fast link: the phone is not on the offered network, or the app lacks the Access Wi-Fi Information entitlement (com.apple.developer.networking.wifi-info)", context: [ - "linkId": link.linkId, - ]) - self.endFastLink(reason: "failed") - } else { - self.scheduleFastLinkRedial(link) - } - return - } - link.networkUnknown = 0 - if network.ssid == link.ssid { - self.openFastLinkStream(link, port: port) - } else { - self.scheduleFastLinkRedial(link) - } + // network. The host is the group's owner, so the phone is on the + // group exactly when its Wi-Fi path's gateway is the offered host. + // Not `NEHotspotNetwork.fetchCurrent`: a `joinOnce` network is not + // one the app configured as iOS counts it, so without location + // permission that names no network at all, and every join failed. + // Until the phone is on it, the dial waits; the engine's deadline + // bounds the wait. + let monitor = NWPathMonitor(requiredInterfaceType: .wifi) + monitor.pathUpdateHandler = { [weak self] path in + // One look per dial. The handler holds the monitor, so it is + // dropped here or each redial would keep one alive. + monitor.pathUpdateHandler = nil + monitor.cancel() + guard let self = self, self.fastLink === link else { return } + if Self.isGateway(link.host, of: path) { + self.openFastLinkStream(link, port: port) + } else { + self.scheduleFastLinkRedial(link) + } + } + monitor.start(queue: linkQueue) + } + + /// Whether `host`, an IP literal, is a gateway of `path`. + private static func isGateway(_ host: String, of path: NWPath) -> Bool { + let v4 = IPv4Address(host) + let v6 = IPv6Address(host) + return path.gateways.contains { gateway in + switch gateway { + case let .hostPort(host: .ipv4(address), port: _): + return address.rawValue == v4?.rawValue + case let .hostPort(host: .ipv6(address), port: _): + return address.rawValue == v6?.rawValue + default: + return false } } } diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index 7317b45a5..fd7e077e9 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4619,9 +4619,8 @@ export class OfflineProtocol { * changes once when the host answers with a network it already had. On iOS the join shows a system * prompt and takes the phone off its own Wi-Fi while the link lasts, and * the link ends when the app leaves the foreground, so ask for it when a - * transfer is worth that. Needs the Hotspot Configuration and Access Wi-Fi - * Information entitlements on iOS 14 or later, and `NEARBY_WIFI_DEVICES` - * (fine location below Android 13) on Android. + * transfer is worth that. Needs the Hotspot Configuration entitlement on iOS, + * and `NEARBY_WIFI_DEVICES` (fine location below Android 13) on Android. * * Rejects when the peer has not advertised support, there is no confirmed * session or live Bluetooth link to it, a peer stream already reaches it, diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index f784f6426..081edd415 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20415,6 +20415,28 @@ mod tests { } } + /// An iPhone confirms it is on a fast link's network by the Wi-Fi path's + /// gateway, never by `NEHotspotNetwork.fetchCurrent`. A `joinOnce` + /// network is not one the app configured as iOS counts it, so without + /// location permission `fetchCurrent` names no network at all: on an + /// iPhone 16 every join was given up `failed` five seconds after the + /// phone was on the group. The Android host names the group's owner + /// address in its offer, and that address is the gateway of the path. + #[test] + fn an_iphone_confirms_the_fast_link_network_by_its_gateway() { + let swift = rn_source_code_only("ios/WifiDirectManager.swift"); + assert!( + !swift.contains("fetchCurrent"), + "ios/WifiDirectManager.swift: NEHotspotNetwork.fetchCurrent names no joinOnce \ + network without location permission; confirm the network by the gateway" + ); + assert!( + swift.contains("if Self.isGateway(link.host, of: path) { self.openFastLinkStream(link, port: port) }"), + "ios/WifiDirectManager.swift: a fast-link dial must wait for the offered host to \ + be the Wi-Fi path's gateway" + ); + } + #[test] fn react_native_android_wifi_direct_callback_does_not_wait_for_a_manager() { let code = diff --git a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md index 488b471c8..75bd35607 100644 --- a/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -152,13 +152,15 @@ session, and only uses it. application should ask for a link when a transfer is worth that, and expect it to end when the user leaves. - An iOS application that uses it needs the Hotspot Configuration entitlement - (`com.apple.developer.networking.HotspotConfiguration`), the Access Wi-Fi - Information entitlement (`com.apple.developer.networking.wifi-info`), and - local-network permission. The second is what lets - `NEHotspotNetwork.fetchCurrent` name the network the phone is on, which the - iPhone checks before it dials: a join can finish with no error while the - phone stays on its own Wi-Fi. An Android application needs `NEARBY_WIFI_DEVICES` on Android 13 - and later, and fine location below it. + (`com.apple.developer.networking.HotspotConfiguration`) and local-network + permission. A join can finish with no error while the phone stays on its + own Wi-Fi, so the iPhone dials only once its Wi-Fi path's gateway is the + offered host, the group's owner. Not by the network's name: + `NEHotspotNetwork.fetchCurrent` names no `joinOnce` network without + location permission, since iOS does not count it as one the application + configured, and on an iPhone 16 every join failed that way. An Android + application needs `NEARBY_WIFI_DEVICES` on Android 13 and later, and fine + location below it. - A fast link and Wi-Fi Direct group formation (`wifiDirect.autoAccept`) share the one group an Android device can own: while either holds it, the other is refused. diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index 06e9adc9d..8d1106d71 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -132,23 +132,16 @@ only when you are ready to show that flow. `requestFastLink` ([ADR 0038](adr/0038-a-fast-link-is-offered-inside-the-session.md)) brings up a Wi-Fi network between this device and a peer it meets over -Bluetooth. An iPhone joins the network the peer hosts, which needs two -capabilities in the app's entitlements (Xcode adds each to the App ID with -automatic signing): - -- **Hotspot Configuration** - (`com.apple.developer.networking.HotspotConfiguration`), to join the - network. -- **Access Wi-Fi Information** (`com.apple.developer.networking.wifi-info`), - to confirm the phone is on that network before it dials. iOS can finish a - join with no error while the phone stays on its own Wi-Fi, and the dial - would then go to an address on the user's home network. +Bluetooth. An iPhone joins the network the peer hosts, which needs the +**Hotspot Configuration** capability +(`com.apple.developer.networking.HotspotConfiguration`) in the app's +entitlements (Xcode adds it to the App ID with automatic signing). Without it +every join ends `failed`. Keep the local-network keys above too, since the stream is a local-network -connection. Without either entitlement every join ends `failed`, the second -with a diagnostic that names it. An iPhone joins from iOS 14, which can say -what network the phone is on; below it a request is refused and a peer's -offer answered `cannot_join`. +connection. No location permission and no Access Wi-Fi Information +entitlement are needed: the iPhone confirms it is on the offered network by +its Wi-Fi gateway, which is the host, not by the network's name. iOS shows "“App” Wants to Join Wi‑Fi Network “DIRECT-…”?" on every join, and the phone leaves its own Wi-Fi while the link lasts. By default a peer's app diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 5037c39bd..5cd335aa5 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1478,9 +1478,11 @@ the host's address and can hand them on, and a peer that shares a session can already send anything. A hostile session peer can offer a network it controls and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial -stays on the group (an iPhone dials only once iOS reports it is on the -offered network, since a join can finish with no error while the phone stays -on its own Wi-Fi; the offered name must be a Wi-Fi Direct group's, and an +stays on the group (an iPhone dials only once its Wi-Fi path's gateway is +the offered address, the group's owner, since a join can finish with no error +while the phone stays on its own Wi-Fi; an offer naming the user's own +router's address would reach the router, which proves nothing and is closed; +the offered name must be a Wi-Fi Direct group's, and an offer naming the network the iPhone is already on, which iOS reports as already joined, ends `invalid` and is never dialled; an Android, which keeps its own Wi-Fi, dials the group owner's address and not the offer's), and the From 7de6b4b9cd667d4af538f93b449e8297d4428cdd Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 16:15:35 +0530 Subject: [PATCH 71/81] fix(bindings): an android host records its fast-link group once it sees it android reports the device out of any group while createGroup is still forming one, which cleared the name written before it. a host killed while hosting left its group on the air with nothing on disk, and the next start adopted it as an ordinary group. device-checked: the group is now removed on restart. --- .../com/offlineprotocol/WifiDirectManager.kt | 6 ++++++ crates/offline-protocol-uniffi/src/lib.rs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 208353f0b..2eaa3f1b4 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1706,6 +1706,12 @@ class WifiDirectManager( val host = groupOwnerAddress if (port == null || host == null) return@requestGroupInfo hosted.reported = true + // Recorded again now the group is seen: Android reports the + // device out of any group while createGroup is still forming + // one, and [fastLinkGroupGone] clears the record written + // before it, so a process that died while hosting left the + // group with no name on disk and the next start adopted it. + recordHostedFastLinkGroup(hosted.ssid) try { protocol.wifiDirectFastLinkHosting(hosted.linkId, host, port.toUShort()) } catch (e: Exception) { diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 081edd415..cff196498 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20436,6 +20436,24 @@ mod tests { be the Wi-Fi path's gateway" ); } + /// An Android host records its fast link's group name once it sees the + /// group, not only before `createGroup`. Android reports the device out of + /// any group while the group is still forming, which clears the first + /// record, so a host killed while hosting left the group on the air with + /// no name on disk and its next start adopted it as an ordinary group. + #[test] + fn an_android_host_records_its_group_once_it_sees_it() { + let kotlin = + rn_source_code_only("android/src/main/java/com/offlineprotocol/WifiDirectManager.kt"); + assert!( + kotlin.contains( + "if (port == null || host == null) return@requestGroupInfo \ + hosted.reported = true recordHostedFastLinkGroup(hosted.ssid)" + ), + "WifiDirectManager.kt: fastLinkGroupChanged must record the hosted group's name \ + when it first sees the group" + ); + } #[test] fn react_native_android_wifi_direct_callback_does_not_wait_for_a_manager() { From 7ff42633b3293b0eaf7eebd6b654df822e47b844 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:10:01 +0530 Subject: [PATCH 72/81] fix(bindings): an iphone gives up a join that never reaches the group the gateway check had no bound: a join that apply reported done while the phone stayed on its own wi-fi waited out its two-minute offer with nothing said, and the host's group refused every other link meanwhile. after ten looks, twenty seconds, it now ends failed with a diagnostic. --- .../react-native/ios/WifiDirectManager.swift | 21 +++++++++++++++++-- crates/offline-protocol-uniffi/src/lib.rs | 14 ++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index bedb983c0..4b3e505c3 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -875,6 +875,8 @@ private final class FastLinkJoin { let deadline: TimeInterval /// iOS reported the join. var joined = false + /// Looks in a row, one per redial, that found the phone off the group. + var offGroup = 0 /// The stream dialed toward the host for this link. weak var stream: AnyObject? @@ -898,6 +900,14 @@ private final class FastLinkJoin { extension WifiDirectManager { /// Gives a dial this long to become ready before it is tried again. private static let FAST_LINK_REDIAL: TimeInterval = 2.0 + /// Looks in a row, one per redial, in which the Wi-Fi path's gateway is + /// not the offered host, before the join is given up as `failed`. `apply` + /// can finish with no error while the phone stays on its own Wi-Fi (a + /// wrong passphrase, a group already gone), and the link would otherwise + /// wait out its offer, two minutes, with nothing said and the host's + /// group refusing every other link. Twenty seconds: on an iPhone 16 the + /// group's address arrived about 3 s after the join. + private static let FAST_LINK_OFF_GROUP_LIMIT = 10 /// Whether `error` is the hotspot error `code`. The domain is checked: /// another framework's error that shares the number would otherwise read @@ -1024,8 +1034,8 @@ extension WifiDirectManager { // Not `NEHotspotNetwork.fetchCurrent`: a `joinOnce` network is not // one the app configured as iOS counts it, so without location // permission that names no network at all, and every join failed. - // Until the phone is on it, the dial waits; the engine's deadline - // bounds the wait. + // Until the phone is on it, the dial waits, for at most + // FAST_LINK_OFF_GROUP_LIMIT looks. let monitor = NWPathMonitor(requiredInterfaceType: .wifi) monitor.pathUpdateHandler = { [weak self] path in // One look per dial. The handler holds the monitor, so it is @@ -1034,8 +1044,15 @@ extension WifiDirectManager { monitor.cancel() guard let self = self, self.fastLink === link else { return } if Self.isGateway(link.host, of: path) { + link.offGroup = 0 self.openFastLinkStream(link, port: port) + } else if link.offGroup + 1 >= Self.FAST_LINK_OFF_GROUP_LIMIT { + self.emitDiagnostic("error", "Fast link: the phone is not on the offered network", context: [ + "linkId": link.linkId, + ]) + self.endFastLink(reason: "failed") } else { + link.offGroup += 1 self.scheduleFastLinkRedial(link) } } diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index cff196498..f07e2ea96 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20422,6 +20422,9 @@ mod tests { /// iPhone 16 every join was given up `failed` five seconds after the /// phone was on the group. The Android host names the group's owner /// address in its offer, and that address is the gateway of the path. + /// The wait for it is bounded: `apply` can finish with no error while the + /// phone stays on its own Wi-Fi, and an unbounded wait held the host's + /// group for the offer's two minutes with nothing said. #[test] fn an_iphone_confirms_the_fast_link_network_by_its_gateway() { let swift = rn_source_code_only("ios/WifiDirectManager.swift"); @@ -20431,10 +20434,19 @@ mod tests { network without location permission; confirm the network by the gateway" ); assert!( - swift.contains("if Self.isGateway(link.host, of: path) { self.openFastLinkStream(link, port: port) }"), + swift.contains( + "if Self.isGateway(link.host, of: path) { link.offGroup = 0 \ + self.openFastLinkStream(link, port: port) }" + ), "ios/WifiDirectManager.swift: a fast-link dial must wait for the offered host to \ be the Wi-Fi path's gateway" ); + assert!( + swift.contains("} else if link.offGroup + 1 >= Self.FAST_LINK_OFF_GROUP_LIMIT {") + && swift.contains("self.endFastLink(reason: \"failed\")"), + "ios/WifiDirectManager.swift: a join that never reaches the group must end \ + `failed` after a bounded number of looks, not wait out its offer" + ); } /// An Android host records its fast link's group name once it sees the /// group, not only before `createGroup`. Android reports the device out of From c293b374115272373fa45c7a02a5a6c07db22eae Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:11:22 +0530 Subject: [PATCH 73/81] fix(bindings): an android host keeps its group's name while the group forms the out-of-group broadcast that arrives during createGroup cleared the name before the group was first seen, so a host killed in that window still left its group adopted on restart. the broadcast now leaves the name alone while the hosted group is unseen, and a failed createGroup clears it. --- .../main/java/com/offlineprotocol/WifiDirectManager.kt | 9 ++++++++- crates/offline-protocol-uniffi/src/lib.rs | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 2eaa3f1b4..53cd8c798 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1589,6 +1589,7 @@ class WifiDirectManager( override fun onFailure(reason: Int) { if (fastLinkHosted !== hosted) return fastLinkHosted = null + recordHostedFastLinkGroup(null) emitDiagnostic("warning", "Fast link: the network did not come up", mapOf( "reason" to reasonToString(reason), )) @@ -1756,7 +1757,13 @@ class WifiDirectManager( /** This device left whatever group it was in. */ private fun fastLinkGroupGone() { fastLinkLeaving = false - recordHostedFastLinkGroup(null) + // Not while a hosted group is still forming: Android reports the + // device out of any group while createGroup brings one up, and + // clearing the name then left a host killed before the group was + // seen with its group on the air and nothing on disk. The group was + // never seen, so this cannot be it going; a failed createGroup clears + // the name itself. + if (fastLinkHosted?.reported != false) recordHostedFastLinkGroup(null) parkedFastLinkJoin?.let { parked -> parkedFastLinkJoin = null try { diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index f07e2ea96..62a7b0247 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20453,6 +20453,8 @@ mod tests { /// any group while the group is still forming, which clears the first /// record, so a host killed while hosting left the group on the air with /// no name on disk and its next start adopted it as an ordinary group. + /// That broadcast also leaves the record alone while the hosted group is + /// unseen, which closes the window before the group is first seen. #[test] fn an_android_host_records_its_group_once_it_sees_it() { let kotlin = @@ -20465,6 +20467,14 @@ mod tests { "WifiDirectManager.kt: fastLinkGroupChanged must record the hosted group's name \ when it first sees the group" ); + assert!( + kotlin.contains( + "private fun fastLinkGroupGone() { fastLinkLeaving = false \ + if (fastLinkHosted?.reported != false) recordHostedFastLinkGroup(null)" + ), + "WifiDirectManager.kt: the out-of-group broadcast during createGroup must not clear \ + the name of a hosted group not yet seen" + ); } #[test] From a96541415c89efcd62cd661af6b1c55e76a1348b Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:16:54 +0530 Subject: [PATCH 74/81] docs: an offer's host is the network's gateway, which an iphone joiner relies on --- docs/spec/control-messages.md | 2 +- docs/state-machines/fast-link.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index 33ed9a97e..b1e9d61f4 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -482,7 +482,7 @@ random: | `kind` | Further fields | Meaning | |--------|----------------|---------| | `request` | none | The sender can join a network and asks the recipient to host one | -| `offer` | `ssid`, `passphrase`, `host`, `port`, `issued_at_ms`, `ttl_ms`, and `re` when it is sent again for a request under another id | The sender is hosting a network for the recipient: join `ssid` with `passphrase` and dial `host:port`, within `ttl_ms` of arrival. `re` names the request it answers; left out otherwise | +| `offer` | `ssid`, `passphrase`, `host`, `port`, `issued_at_ms`, `ttl_ms`, and `re` when it is sent again for a request under another id | The sender is hosting a network for the recipient: join `ssid` with `passphrase` and dial `host:port`, within `ttl_ms` of arrival. `host` is the sender's own address on that network, which is the network's gateway (the group's owner): an iPhone confirms it has joined by its Wi-Fi gateway being `host`, since iOS names no network the application joined for one session, and ends the join `failed` after about 20 s otherwise. `re` names the request it answers; left out otherwise | | `close` | `reason` | The link with this id is over | Four rules hold for every frame of the family: diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 7a9f3974d..324e927e8 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -48,7 +48,7 @@ wake-up that drains outbound stream bodies: | Directive | The platform | Then reports | |-----------|--------------|--------------| | `host` | Brings up a network with the given name and passphrase, admitting the given peer only | `wifi_direct_fast_link_hosting(link, host, port)`, or `wifi_direct_fast_link_ended(link, reason)` | -| `join` | Joins the given network and, once the system reports it is on it, dials `host:port` (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | +| `join` | Joins the given network and, once it is on it, dials `host:port` (an iPhone knows it is on it when its Wi-Fi path's gateway is `host`, and ends the join `failed` after 10 looks, 2 s apart, that find otherwise) (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | | `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | A platform declares what it can do with From 3601f2a02f567a5c23d0820a880157629680b0d9 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:16:54 +0530 Subject: [PATCH 75/81] fix(bindings): an iphone's fast-link dial retries when the stream table is full returning ended the redial chain, so a join that reached the group with the table full sat out its two-minute offer with the host's group on the air. the deadline still bounds the retries. --- .../react-native/ios/WifiDirectManager.swift | 17 +++++++++++++---- crates/offline-protocol-uniffi/src/lib.rs | 8 ++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 4b3e505c3..ec93ffd84 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -1023,8 +1023,14 @@ extension WifiDirectManager { scheduleFastLinkRedial(link) return } - guard streams.count < Self.MAX_STREAMS, - let port = NWEndpoint.Port(rawValue: link.port) else { return } + guard let port = NWEndpoint.Port(rawValue: link.port) else { return } + // A full stream table is a "not yet" like any other: returning ended + // the redial chain, and the join sat out its offer with the host's + // group on the air. The deadline above still bounds it. + guard streams.count < Self.MAX_STREAMS else { + scheduleFastLinkRedial(link) + return + } // Dialed only from the offered network. `apply` can finish with no // error while the phone stays on its own Wi-Fi (a wrong passphrase, // a group already gone), and `.wifi` alone would then send the dial, @@ -1079,8 +1085,11 @@ extension WifiDirectManager { /// only, and only once the phone is on the link's network. private func openFastLinkStream(_ link: FastLinkJoin, port: NWEndpoint.Port) { guard link.joined, state == .running, - ProcessInfo.processInfo.systemUptime < link.deadline, - streams.count < Self.MAX_STREAMS else { return } + ProcessInfo.processInfo.systemUptime < link.deadline else { return } + guard streams.count < Self.MAX_STREAMS else { + scheduleFastLinkRedial(link) + return + } if let held = peers.handle(for: link.peer), streams.contains(held) { return } if let current = link.stream as? Stream, streams.contains(current) { scheduleFastLinkRedial(link) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 62a7b0247..901bef0e7 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20447,6 +20447,14 @@ mod tests { "ios/WifiDirectManager.swift: a join that never reaches the group must end \ `failed` after a bounded number of looks, not wait out its offer" ); + assert_eq!( + swift + .matches("guard streams.count < Self.MAX_STREAMS else { scheduleFastLinkRedial(link) return }") + .count(), + 2, + "ios/WifiDirectManager.swift: a fast-link dial that finds the stream table full \ + must try again, not end the redial chain" + ); } /// An Android host records its fast link's group name once it sees the /// group, not only before `createGroup`. Android reports the device out of From d94483b14e6eae97e4c969494dc749c7526689bc Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:32:42 +0530 Subject: [PATCH 76/81] fix(bindings): an iphone refuses an offer whose host is already its gateway the gateway check could not tell the offered group from the user's own network when the offer named the home router: a join that silently did not happen was dialled there on every redial until the offer expired. before the prompt the host must not already be the wi-fi gateway, looked at up to four times so a phone still leaving a previous group is not refused. device-checked: a join and an immediate re-link both reach the prompt. --- .../react-native/ios/WifiDirectManager.swift | 63 ++++++++++++++++--- crates/offline-protocol-uniffi/src/lib.rs | 22 ++++++- docs/security/threat-model.md | 5 +- docs/state-machines/fast-link.md | 2 +- 4 files changed, 77 insertions(+), 15 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index ec93ffd84..363c61e75 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -908,6 +908,10 @@ extension WifiDirectManager { /// group refusing every other link. Twenty seconds: on an iPhone 16 the /// group's address arrived about 3 s after the join. private static let FAST_LINK_OFF_GROUP_LIMIT = 10 + /// Looks before the prompt, 2 s apart, that find the offered host already + /// the gateway before the offer is refused `invalid`. Eight seconds: a + /// phone leaving a fast link's group was back on its own Wi-Fi in about 4. + private static let FAST_LINK_PRE_JOIN_LOOKS = 4 /// Whether `error` is the hotspot error `code`. The domain is checked: /// another framework's error that shares the number would otherwise read @@ -961,14 +965,58 @@ extension WifiDirectManager { deadline: ProcessInfo.processInfo.systemUptime + TimeInterval(directive.expiresInMs) / 1000 ) fastLink = link + checkBeforeJoin(link, passphrase: passphrase, looks: 0) + } + + /// Before the prompt, the offered host must not already be the gateway of + /// the network the phone is on. The dial goes out once the Wi-Fi gateway + /// is the host (`dialFastLink`), and `apply` can finish with no error + /// while the phone stays on its own Wi-Fi, so an offer naming the user's + /// own router would otherwise be dialled there, again on every redial + /// until the offer expired. A match is looked at again before it is + /// refused: right after a link ends the phone is still leaving that + /// group, whose owner has the same address as every Android group's. + private func checkBeforeJoin(_ link: FastLinkJoin, passphrase: String, looks: Int) { + lookAtWifiPath { [weak self] path in + guard let self = self, self.fastLink === link else { return } + if !Self.isGateway(link.host, of: path) { + self.applyFastLinkJoin(link, passphrase: passphrase) + } else if looks + 1 < Self.FAST_LINK_PRE_JOIN_LOOKS { + self.linkQueue.asyncAfter(deadline: .now() + Self.FAST_LINK_REDIAL) { [weak self] in + self?.checkBeforeJoin(link, passphrase: passphrase, looks: looks + 1) + } + } else { + self.emitDiagnostic("warning", "Fast link: the offered host is the gateway of the network the phone is already on", context: [ + "linkId": link.linkId, + ]) + self.fastLink = nil + self.protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "invalid") + } + } + } + + private func applyFastLinkJoin(_ link: FastLinkJoin, passphrase: String) { emitDiagnostic("info", "Fast link: joining a network", context: ["linkId": link.linkId]) - let configuration = NEHotspotConfiguration(ssid: ssid, passphrase: passphrase, isWEP: false) + let configuration = NEHotspotConfiguration(ssid: link.ssid, passphrase: passphrase, isWEP: false) configuration.joinOnce = true NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] error in self?.linkQueue.async { self?.fastLinkJoinFinished(link, error: error as NSError?) } } } + /// One look at the Wi-Fi path, on linkQueue. The handler holds the + /// monitor, so it is dropped on the first update or each look would keep + /// one alive. + private func lookAtWifiPath(_ body: @escaping (NWPath) -> Void) { + let monitor = NWPathMonitor(requiredInterfaceType: .wifi) + monitor.pathUpdateHandler = { path in + monitor.pathUpdateHandler = nil + monitor.cancel() + body(path) + } + monitor.start(queue: linkQueue) + } + private func fastLinkJoinFinished(_ link: FastLinkJoin, error: NSError?) { guard fastLink === link else { // Closed while the user read the prompt: leave what was joined. @@ -1036,18 +1084,14 @@ extension WifiDirectManager { // a group already gone), and `.wifi` alone would then send the dial, // and the preamble, to whatever the offer named on the user's home // network. The host is the group's owner, so the phone is on the - // group exactly when its Wi-Fi path's gateway is the offered host. - // Not `NEHotspotNetwork.fetchCurrent`: a `joinOnce` network is not + // group exactly when its Wi-Fi path's gateway is the offered host; + // `checkBeforeJoin` refused a host that was already the gateway of + // the network the phone was on. Not `NEHotspotNetwork.fetchCurrent`: a `joinOnce` network is not // one the app configured as iOS counts it, so without location // permission that names no network at all, and every join failed. // Until the phone is on it, the dial waits, for at most // FAST_LINK_OFF_GROUP_LIMIT looks. - let monitor = NWPathMonitor(requiredInterfaceType: .wifi) - monitor.pathUpdateHandler = { [weak self] path in - // One look per dial. The handler holds the monitor, so it is - // dropped here or each redial would keep one alive. - monitor.pathUpdateHandler = nil - monitor.cancel() + lookAtWifiPath { [weak self] path in guard let self = self, self.fastLink === link else { return } if Self.isGateway(link.host, of: path) { link.offGroup = 0 @@ -1062,7 +1106,6 @@ extension WifiDirectManager { self.scheduleFastLinkRedial(link) } } - monitor.start(queue: linkQueue) } /// Whether `host`, an IP literal, is a gateway of `path`. diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 901bef0e7..85ccf2b0e 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20422,6 +20422,10 @@ mod tests { /// iPhone 16 every join was given up `failed` five seconds after the /// phone was on the group. The Android host names the group's owner /// address in its offer, and that address is the gateway of the path. + /// Before the prompt the host must not already be the gateway of the + /// network the phone is on: otherwise an offer naming the user's own + /// router, with a join that silently did not happen, was dialled there on + /// every redial. /// The wait for it is bounded: `apply` can finish with no error while the /// phone stays on its own Wi-Fi, and an unbounded wait held the host's /// group for the offer's two minutes with nothing said. @@ -20442,8 +20446,11 @@ mod tests { be the Wi-Fi path's gateway" ); assert!( - swift.contains("} else if link.offGroup + 1 >= Self.FAST_LINK_OFF_GROUP_LIMIT {") - && swift.contains("self.endFastLink(reason: \"failed\")"), + swift.contains( + "} else if link.offGroup + 1 >= Self.FAST_LINK_OFF_GROUP_LIMIT { \ + self.emitDiagnostic(\"error\", \"Fast link: the phone is not on the offered network\", \ + context: [ \"linkId\": link.linkId, ]) self.endFastLink(reason: \"failed\") }" + ), "ios/WifiDirectManager.swift: a join that never reaches the group must end \ `failed` after a bounded number of looks, not wait out its offer" ); @@ -20455,6 +20462,17 @@ mod tests { "ios/WifiDirectManager.swift: a fast-link dial that finds the stream table full \ must try again, not end the redial chain" ); + assert!( + swift.contains( + "fastLink = link checkBeforeJoin(link, passphrase: passphrase, looks: 0) }" + ) && swift.contains( + "if !Self.isGateway(link.host, of: path) { \ + self.applyFastLinkJoin(link, passphrase: passphrase) }" + ), + "ios/WifiDirectManager.swift: a join must refuse an offered host that is already \ + the gateway of the network the phone is on, before the prompt; the gateway check \ + alone dials the user's own router when the join silently does not happen" + ); } /// An Android host records its fast link's group name once it sees the /// group, not only before `createGroup`. Android reports the device out of diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 5cd335aa5..31e8eef90 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1480,8 +1480,9 @@ and so take the joiner off its own Wi-Fi, after the system prompt on iOS. The offered address must be a private or link-local IP literal, the joiner's dial stays on the group (an iPhone dials only once its Wi-Fi path's gateway is the offered address, the group's owner, since a join can finish with no error -while the phone stays on its own Wi-Fi; an offer naming the user's own -router's address would reach the router, which proves nothing and is closed; +while the phone stays on its own Wi-Fi; an offer whose address is already +the gateway of the network the iPhone is on, the user's own router, ends +`invalid` before the prompt and is never dialled; the offered name must be a Wi-Fi Direct group's, and an offer naming the network the iPhone is already on, which iOS reports as already joined, ends `invalid` and is never dialled; an Android, which keeps its own Wi-Fi, dials the group diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 324e927e8..2b568b230 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -48,7 +48,7 @@ wake-up that drains outbound stream bodies: | Directive | The platform | Then reports | |-----------|--------------|--------------| | `host` | Brings up a network with the given name and passphrase, admitting the given peer only | `wifi_direct_fast_link_hosting(link, host, port)`, or `wifi_direct_fast_link_ended(link, reason)` | -| `join` | Joins the given network and, once it is on it, dials `host:port` (an iPhone knows it is on it when its Wi-Fi path's gateway is `host`, and ends the join `failed` after 10 looks, 2 s apart, that find otherwise) (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | +| `join` | Joins the given network and, once it is on it, dials `host:port` (an iPhone knows it is on it when its Wi-Fi path's gateway is `host`, and ends the join `failed` after 10 looks, 2 s apart, that find otherwise; a `host` that is already its gateway before the prompt, over 4 looks, ends the join `invalid`, since the dial would go to the user's own router) (Android dials the group owner's own address with that port, since it stays on its own Wi-Fi), claiming the given peer | the stream's preamble, through `wifi_direct_peer_connected`, or `wifi_direct_fast_link_ended(link, reason)` | | `close` | Ends the stream it opened for the link and leaves or removes the network | nothing | A platform declares what it can do with From 0a014d1b99bf7863d7baa442e9d651b5f7a281f9 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:42:44 +0530 Subject: [PATCH 77/81] fix(protocol): a pending fast link gives way to a stream that reached the peer first two phones back on one home network met over it while an offer was pending; the engine took that stream for the link's own and marked the link up, the iphone never dialled the group its user had just joined, and leaving the home network for it lost both. a platform now ends the link superseded before announcing a stream that is not the link's own, and answers a directive for a peer a stream already reaches the same way. the end never counts against the peer and fails no transfer on the slot. --- CHANGELOG.md | 4 +- .../OfflineProtocol.Sdk/Generated/Enums.g.cs | 2 +- .../Generated/LocalApiClients.g.cs | 2 +- .../Generated/ProtocolConfig.g.cs | 2 +- .../ProtocolEngine.LocalApi.part01.g.cs | 2 +- .../ProtocolEngine.LocalApi.part02.g.cs | 2 +- .../ProtocolEngine.LocalApi.part03.g.cs | 2 +- .../Generated/ProtocolEngine.Static.g.cs | 2 +- .../offline_protocol_sdk/local_api/table.py | 2 +- .../com/offlineprotocol/PeerStreamSockets.kt | 3 + .../com/offlineprotocol/WifiDirectManager.kt | 38 +++++++++- .../react-native/ios/WifiDirectManager.swift | 20 ++++++ bindings/react-native/src/types.ts | 3 +- crates/offline-protocol-uniffi/src/lib.rs | 58 +++++++++++++++- .../src/offline_protocol.udl | 6 +- crates/offline-protocol/src/fast_link.rs | 69 ++++++++++++++++++- docs/spec/control-messages.md | 4 +- docs/state-machines/fast-link.md | 13 +++- 18 files changed, 213 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 392a96d83..01d490cf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,9 @@ Questions about a release, or about upgrading to one? Ask in the it on their own: a 1 MiB file that took 197.7 s over Bluetooth took about 2.5 s on two phones. Progress arrives as `fast_link_changed` events; the link ends after 60 s with nothing large to carry, when the iPhone app leaves - the foreground, or on `closeFastLink`. An iOS app needs the Hotspot + the foreground, or on `closeFastLink`, and ends `superseded` when another + connection, a shared home network say, reaches the peer before it comes up + and carries the traffic instead. An iOS app needs the Hotspot Configuration entitlement, and an Android app `NEARBY_WIFI_DEVICES` (fine location below Android 13); see [mobile permissions](docs/mobile-permissions.md#fast-link). `wifiDirect.fastLink` decides how far an app takes part: `any` (the diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs index ffc8de061..d8a4dc682 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/Enums.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs index ffa10bca2..4cbba8717 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/LocalApiClients.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs index 84bb98c5b..42ac2d163 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolConfig.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs index 6738f7b28..67f8abc8a 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part01.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs index f53a70dae..64c0bcf85 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part02.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs index 3608dc518..c5cff6404 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.LocalApi.part03.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs index 560ff281e..172440bd4 100644 --- a/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs +++ b/bindings/csharp/src/OfflineProtocol.Sdk/Generated/ProtocolEngine.Static.g.cs @@ -1,6 +1,6 @@ // // Generated by tools/gen_csharp_local_api.py from offline_protocol.udl -// UDL_SHA256 = a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable diff --git a/bindings/python/offline_protocol_sdk/local_api/table.py b/bindings/python/offline_protocol_sdk/local_api/table.py index 896975fa4..9ab41ba16 100644 --- a/bindings/python/offline_protocol_sdk/local_api/table.py +++ b/bindings/python/offline_protocol_sdk/local_api/table.py @@ -9,7 +9,7 @@ from __future__ import annotations -UDL_SHA256 = "a9930bed7a38cd46b1a2b7075ff76a1b06930abd79fa3d0cbe97ab0e68a7d3bc" +UDL_SHA256 = "d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80" TABLE = {'callbacks': ('MlsStorageProvider', 'ProtocolStateStorageProvider', diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt index e4243dea1..6eca37389 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/PeerStreamSockets.kt @@ -179,6 +179,9 @@ internal class PeerStreamSockets( /** Whether a stream holds [address] now. */ fun holds(address: String): Boolean = links.handleFor(address) != null + /** The carrier of the stream holding [address] now, if any. */ + fun carrierOf(address: String): Carrier? = links.handleFor(address)?.carrier + /** Whether an outbound socket would find a free slot now. */ fun hasRoom(): Boolean = synchronized(admission) { reserved < limits.maxStreams } diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 53cd8c798..ed4c04ee8 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -213,8 +213,10 @@ class WifiDirectManager( override fun verify(assertion: ByteArray): String = verifyIdentityAssertion(assertion.map { it.toUByte() }) - override fun peerConnected(address: String) = + override fun peerConnected(address: String) { + supersedeFastLinkFor(address) protocol.wifiDirectPeerConnected(address) + } override fun messageReceived(address: String, body: ByteArray) = protocol.wifiDirectMessageReceived(address, body.map { it.toUByte() }) @@ -1550,6 +1552,28 @@ class WifiDirectManager( } } + /** + * A stream that is not the fast link's own, one over the shared LAN, + * proved the peer of a link not yet up (both devices back on one home + * network): the link is ended `superseded` before the stream is + * announced. Announced first, the engine took it for the link's and + * marked the link up, the joiner never dialled the group, and leaving the + * home network for it then lost both. Called on a socket thread, before + * the announcement: the link's fields are read once, and the group is + * let go on the transport looper. + */ + private fun supersedeFastLinkFor(address: String) { + if (sockets.carrierOf(address) != PeerStreamSockets.Carrier.LAN) return + val linkId = fastLinkHosted?.takeIf { it.peer == address }?.linkId + ?: fastLinkJoined?.takeIf { it.peer == address }?.linkId + ?: return + emitDiagnostic("info", "Fast link: another stream reached the peer first", mapOf( + "linkId" to linkId, + )) + fastLinkEnded(linkId, "superseded") + transportHandler.post { closeFastLink(linkId) } + } + private fun fastLinkEnded(linkId: String, reason: String) { try { protocol.wifiDirectFastLinkEnded(linkId, reason) @@ -1569,6 +1593,12 @@ class WifiDirectManager( */ @SuppressLint("MissingPermission") private fun hostFastLink(directive: FastLinkDirective) { + if (sockets.holds(directive.peerId)) { + // A stream already reaches the peer and carries what the link + // would; a group now would only lock out formation for nothing. + fastLinkEnded(directive.linkId, "superseded") + return + } val ssid = directive.ssid val passphrase = directive.passphrase val p2p = wifiP2pManager @@ -1605,6 +1635,12 @@ class WifiDirectManager( */ @SuppressLint("MissingPermission") private fun joinFastLink(directive: FastLinkDirective) { + if (sockets.holds(directive.peerId)) { + // A stream already reaches the peer and carries what the link + // would. + fastLinkEnded(directive.linkId, "superseded") + return + } val ssid = directive.ssid val passphrase = directive.passphrase val host = directive.host diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 363c61e75..8b71a7e20 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -821,6 +821,19 @@ extension WifiDirectManager: PeerStreamHost { } func peerStreamConnected(_ address: String) { + // A stream that is not the fast link's own reached the link's peer + // first (both phones back on one home network): the link is ended + // `superseded` before the stream is announced. Announced first, the + // engine took it for the link's and marked the link up, the join + // never dialled the network the user had just joined, and leaving + // the home network for it then lost both. + if let pending = fastLink, pending.peer == address, + peers.handle(for: address) !== (pending.stream as? Stream) { + emitDiagnostic("info", "Fast link: another stream reached the peer first", context: [ + "linkId": pending.linkId, + ]) + endFastLink(reason: "superseded") + } do { try protocolInstance.wifiDirectPeerConnected(peerId: address) } catch { @@ -964,6 +977,13 @@ extension WifiDirectManager { port: port, deadline: ProcessInfo.processInfo.systemUptime + TimeInterval(directive.expiresInMs) / 1000 ) + // A stream already reaches the peer: it carries what the link would, + // and the prompt would take the phone off the network that stream + // runs on. + if let held = peers.handle(for: link.peer), streams.contains(held) { + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "superseded") + return + } fastLink = link checkBeforeJoin(link, passphrase: passphrase, looks: 0) } diff --git a/bindings/react-native/src/types.ts b/bindings/react-native/src/types.ts index 73b5a1d11..20bdc451b 100644 --- a/bindings/react-native/src/types.ts +++ b/bindings/react-native/src/types.ts @@ -1505,7 +1505,8 @@ export interface FastLinkChangedEvent extends BaseEvent { /** * Why it closed, only on `closed`: `declined` (the joiner's user said no), * `idle`, `lost`, `expired`, `background`, `busy`, `cannot_host`, - * `cannot_join`, and others; an unknown value means it failed. + * `cannot_join`, `superseded` (another connection reached the peer first + * and carries its traffic), and others; an unknown value means it failed. */ reason: string | null; } diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 85ccf2b0e..b42028199 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20474,6 +20474,58 @@ mod tests { alone dials the user's own router when the join silently does not happen" ); } + /// A pending fast link is ended `superseded` when another peer stream + /// reaches its peer first, never taken for the link's own. Both phones + /// back on one home network met over the LAN while an offer was pending: + /// the engine marked the link up from that stream, the iPhone never + /// dialled the group the user had just joined, and leaving the home + /// network for it lost both 40 s later. The announcement pins (in + /// `react_native_wifi_direct_announces_only_proved_addresses`) hold the + /// order, the end before the announcement; this holds the conditions + /// and the directive-time refusals. + #[test] + fn a_pending_fast_link_gives_way_to_a_stream_that_reached_the_peer_first() { + let kotlin = + rn_source_code_only("android/src/main/java/com/offlineprotocol/WifiDirectManager.kt"); + let swift = rn_source_code_only("ios/WifiDirectManager.swift"); + assert!( + swift.contains( + "if let pending = fastLink, pending.peer == address, \ + peers.handle(for: address) !== (pending.stream as? Stream) {" + ), + "ios/WifiDirectManager.swift: a stream that is not the link's own must end a \ + pending link for its peer" + ); + assert!( + swift.contains( + "if let held = peers.handle(for: link.peer), streams.contains(held) { \ + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: \"superseded\") \ + return } fastLink = link" + ), + "ios/WifiDirectManager.swift: a join for a peer a stream already reaches must end \ + `superseded` before any prompt" + ); + assert!( + kotlin.contains( + "private fun supersedeFastLinkFor(address: String) { \ + if (sockets.carrierOf(address) != PeerStreamSockets.Carrier.LAN) return" + ), + "WifiDirectManager.kt: only a LAN stream supersedes a pending link; a P2P one is \ + the link's own" + ); + for directive in ["hostFastLink", "joinFastLink"] { + assert!( + kotlin.contains(&format!( + "private fun {directive}(directive: FastLinkDirective) {{ \ + if (sockets.holds(directive.peerId)) {{ \ + fastLinkEnded(directive.linkId, \"superseded\") return }}" + )), + "WifiDirectManager.kt: {directive} for a peer a stream already reaches must end \ + `superseded` first" + ); + } + } + /// An Android host records its fast link's group name once it sees the /// group, not only before `createGroup`. Android reports the device out of /// any group while the group is still forming, which clears the first @@ -21688,7 +21740,7 @@ mod tests { [ ( "wifiDirectPeerConnected(", - "func peerStreamConnected(_ address: String) { do { \ + "endFastLink(reason: \"superseded\") } do { \ try protocolInstance.wifiDirectPeerConnected(peerId: address)", ), ( @@ -21740,8 +21792,8 @@ mod tests { [ ( "wifiDirectPeerConnected(", - "override fun peerConnected(address: String) = \ - protocol.wifiDirectPeerConnected(address)", + "override fun peerConnected(address: String) { \ + supersedeFastLinkFor(address) protocol.wifiDirectPeerConnected(address) }", ), ( "wifiDirectMessageReceived(", diff --git a/crates/offline-protocol-uniffi/src/offline_protocol.udl b/crates/offline-protocol-uniffi/src/offline_protocol.udl index 86f6ec543..777d9e208 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1515,8 +1515,10 @@ interface OfflineProtocol { // link: `declined` (the user refused the join), `failed`, `host_failed`, // `background` (iOS drops a joined network 15 s after the app leaves // the foreground), `lost` (the network went away), `invalid` (the offer - // named a network the device is already on) or `closed` (the platform - // stopped). Any other token reads as `failed`; the full list is the + // named a network the device is already on), `closed` (the platform + // stopped) or `superseded` (a stream other than the link's own proved + // the peer first; report it before announcing that stream). Any other + // token reads as `failed`; the full list is the // `close` reasons in docs/spec/control-messages.md. The peer is told. void wifi_direct_fast_link_ended(string link_id, string reason); diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 8b21e28ca..4e9624269 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -185,6 +185,13 @@ pub enum CloseReason { Background, /// The application closed it. Closed, + /// Another peer stream, not the link's own, reached the peer before the + /// link came up (two devices back on one home network, say). That stream + /// already carries what the link would, so the link ends rather than + /// count the other stream as its own: taken for the link, it marked the + /// link up, the joiner never dialled the network the user had just + /// joined, and leaving the home network then lost both. + Superseded, } impl CloseReason { @@ -204,6 +211,7 @@ impl CloseReason { Self::Idle => "idle", Self::Background => "background", Self::Closed => "closed", + Self::Superseded => "superseded", } } @@ -223,6 +231,7 @@ impl CloseReason { "idle" => Self::Idle, "background" => Self::Background, "closed" => Self::Closed, + "superseded" => Self::Superseded, _ => Self::Failed, } } @@ -1186,7 +1195,10 @@ impl FastLinks { if !by_peer && matches!( reason, - CloseReason::Declined | CloseReason::Closed | CloseReason::Background + CloseReason::Declined + | CloseReason::Closed + | CloseReason::Background + | CloseReason::Superseded ) { return; @@ -1260,7 +1272,9 @@ impl FastLinks { self.directives .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); - if link.state == FastLinkState::Up { + // A superseded link's peer is still reached, over the other stream, + // and a transfer there is that stream's, not the link's. + if link.state == FastLinkState::Up && reason != CloseReason::Superseded { self.released.push_back(link.peer.clone()); } if link.role == FastLinkRole::Host && link.requested_by_peer { @@ -2704,6 +2718,57 @@ mod tests { ); } + #[test] + fn a_link_another_stream_superseded_never_counts_against_the_peer() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + // Each unasked offer is ended by the iPhone's platform because a + // home-network stream reached the Android first. Counted like an + // ignored offer, two of them paused the Android's next offer for ten + // minutes, though nothing the Android did went unanswered. + for seed in [1, 2, 3] { + let id = android.request(HIGH, fresh(seed), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + let join = iphone + .next_directive(now) + .expect("the offer is joined, not paused"); + assert_eq!(join.kind, FastLinkDirectiveKind::Join); + assert!(iphone.platform_ended(&join.link_id, CloseReason::Superseded, now)); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + android.take_changes(); + iphone.take_changes(); + } + } + + #[test] + fn a_superseded_link_leaves_the_other_streams_transfers_alone() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + let id = android.request(HIGH, fresh(1), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + iphone.next_directive(now); + // A stream proves the peer and the platform then says it was not the + // link's: the peer is still reached over that stream, so a transfer + // on the slot is that stream's and must not be failed. + iphone.take_changes(); + iphone.stream_proved(LOW, now); + assert_eq!(states(&mut iphone), [FastLinkState::Up]); + assert!(iphone.platform_ended(&id, CloseReason::Superseded, now)); + assert!(iphone.take_released().is_empty()); + // The same link lost, by contrast, releases its peer. + android.stream_proved(HIGH, now); + assert!(android.platform_ended(&id, CloseReason::Lost, now)); + assert_eq!(android.take_released(), [HIGH.to_string()]); + assert_eq!(CloseReason::parse("superseded"), CloseReason::Superseded); + assert_eq!(CloseReason::Superseded.as_str(), "superseded"); + } + #[test] fn a_host_closing_its_own_offers_declined_is_still_paused() { let mut android = machine(host_roles()); diff --git a/docs/spec/control-messages.md b/docs/spec/control-messages.md index b1e9d61f4..5a5763f84 100644 --- a/docs/spec/control-messages.md +++ b/docs/spec/control-messages.md @@ -514,7 +514,9 @@ Four rules hold for every frame of the family: `reason` is one of `declined`, `failed`, `host_failed`, `cannot_host`, `cannot_join`, `busy`, `invalid`, `expired`, `no_offer`, `lost`, `idle`, -`background` or `closed`. A receiver treats an unknown reason as `failed`. +`background`, `closed` or `superseded` (another peer stream reached the peer +before the link came up, and carries its traffic instead). A receiver treats +an unknown reason as `failed`. ## The control-plane signature gate diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 2b568b230..5b6045b3f 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -64,7 +64,7 @@ for go ahead and no join prompt or group appears that it did not want. | State | Entered when | Leaves to | |-------|--------------|-----------| | `hosting` | The application asked and this device can host, or a peer's `request` arrived and it can | `offered` on the platform's report; `closed` (`host_failed`) after 20 s without one, or on the platform's `ended` | -| `offered` | The platform reported the network up; the `offer` is sent | `up` when a stream proves the peer; `closed` (`expired`) 120 s after the offer was made | +| `offered` | The platform reported the network up; the `offer` is sent | `up` when a stream proves the peer; `closed` (`expired`) 120 s after the offer was made, or (`superseded`) when the platform reports a stream other than the link's proved the peer first | | `up` | A stream proved the peer while the link was `offered` | `closed` on the stream's loss (`lost`), after 60 s idle (`idle`), on `close` from either side | ## The joiner @@ -72,7 +72,7 @@ for go ahead and no join prompt or group appears that it did not want. | State | Entered when | Leaves to | |-------|--------------|-----------| | `requested` | The application asked and this device can only join; the `request` is sent | `joining` on the peer's `offer`; `closed` (`no_offer`) after 30 s, or on the peer's `close` | -| `joining` | An `offer` arrived, by request or not, and this device can join | `up` when a stream proves the host; `closed` (`expired`) at the offer's lifetime, measured from its arrival, or on the platform's `ended` | +| `joining` | An `offer` arrived, by request or not, and this device can join | `up` when a stream proves the host; `closed` (`expired`) at the offer's lifetime, measured from its arrival, or on the platform's `ended` (`superseded` when a stream other than the link's proved the host first) | | `up` | A stream proved the host while the link was `joining` | as for the host | ## Frames that cross a link @@ -232,6 +232,15 @@ passphrase. formation. Hence the admitted peer, and a passphrase only the two hold. - **Two links at once** are two networks on a phone that can join one, and the second join drops the first without either side being told. +- **Another stream taken for the link's own.** Two phones back on one home + network meet over it while an offer is pending. Counted as the link's + stream, it marked the link `up`, the iPhone never dialled the group its user + had just joined, and leaving the home network for it lost both 40 s later. + Hence a platform that sees a stream other than the link's own prove the + link's peer first ends the link `superseded` before announcing the stream, + and answers a directive for a peer a stream already reaches the same way. + Such an end is the platform's own and never counts against the peer, and + the transfers on the slot are the other stream's, so none is failed. - **A joiner that falls silent** when iOS takes the network away leaves the host's stream half open until keepalive ends it. Hence the platform's report. From 5e106bf4343381843fb11efbaf8bfafccd31c1a0 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 17:53:16 +0530 Subject: [PATCH 78/81] fix(protocol): a stream over the group is the fast link's own, and a reached peer gets no link an android below 13 advertises on its group's interface, so an iphone's general bonjour dial could prove the host over the group before the link's own dial; taken for another stream, it superseded the link and tore down the group it ran on. on ios a stream whose path's gateway is the offered host, once joined, is now adopted as the link's. and the engine answers a request or offer from a peer another stream already reaches superseded itself, with no link: the peer's own superseded could overtake this device's report and count against the peer. --- .../react-native/ios/WifiDirectManager.swift | 23 ++++++-- crates/offline-protocol-uniffi/src/lib.rs | 13 +++-- crates/offline-protocol/src/fast_link.rs | 56 +++++++++++++++++++ .../src/protocol/fast_link.rs | 14 ++++- .../src/protocol/tests/fast_link.rs | 38 +++++++++++++ docs/state-machines/fast-link.md | 11 +++- 6 files changed, 142 insertions(+), 13 deletions(-) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index 8b71a7e20..c5f6e46f3 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -826,13 +826,24 @@ extension WifiDirectManager: PeerStreamHost { // `superseded` before the stream is announced. Announced first, the // engine took it for the link's and marked the link up, the join // never dialled the network the user had just joined, and leaving - // the home network for it then lost both. + // the home network for it then lost both. Only a first announcement + // for the address reaches here, so an up link, whose own stream + // holds the address, never does. if let pending = fastLink, pending.peer == address, - peers.handle(for: address) !== (pending.stream as? Stream) { - emitDiagnostic("info", "Fast link: another stream reached the peer first", context: [ - "linkId": pending.linkId, - ]) - endFastLink(reason: "superseded") + let held = peers.handle(for: address), held !== (pending.stream as? Stream) { + if pending.joined, let path = held.connection.currentPath, + Self.isGateway(pending.host, of: path) { + // Over the group itself, from the general Bonjour dial: an + // Android below 13 advertises on the group's interface too, + // and that dial needs no DHCP address, so it can prove the + // host before the link's own. It is the link's stream. + pending.stream = held + } else { + emitDiagnostic("info", "Fast link: another stream reached the peer first", context: [ + "linkId": pending.linkId, + ]) + endFastLink(reason: "superseded") + } } do { try protocolInstance.wifiDirectPeerConnected(peerId: address) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index b42028199..990c5815f 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20482,7 +20482,8 @@ mod tests { /// network for it lost both 40 s later. The announcement pins (in /// `react_native_wifi_direct_announces_only_proved_addresses`) hold the /// order, the end before the announcement; this holds the conditions - /// and the directive-time refusals. + /// and the directive-time refusals. A stream over the group itself is + /// the link's own however it was dialled. #[test] fn a_pending_fast_link_gives_way_to_a_stream_that_reached_the_peer_first() { let kotlin = @@ -20491,10 +20492,14 @@ mod tests { assert!( swift.contains( "if let pending = fastLink, pending.peer == address, \ - peers.handle(for: address) !== (pending.stream as? Stream) {" + let held = peers.handle(for: address), held !== (pending.stream as? Stream) { \ + if pending.joined, let path = held.connection.currentPath, \ + Self.isGateway(pending.host, of: path) { pending.stream = held } else {" ), "ios/WifiDirectManager.swift: a stream that is not the link's own must end a \ - pending link for its peer" + pending link for its peer, and one over the group itself (its path's gateway \ + the offered host) is the link's own: an Android below 13 advertises on the \ + group's interface, and superseding that stream tore down the group it ran on" ); assert!( swift.contains( @@ -21740,7 +21745,7 @@ mod tests { [ ( "wifiDirectPeerConnected(", - "endFastLink(reason: \"superseded\") } do { \ + "endFastLink(reason: \"superseded\") } } do { \ try protocolInstance.wifiDirectPeerConnected(peerId: address)", ), ( diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index 4e9624269..f61e5b3cd 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -791,6 +791,20 @@ impl FastLinks { } } + /// A `request` or `offer` from `peer` arrived while another peer stream + /// already reaches it, and this device holds no link with it: answered + /// `superseded` as this device's own end, with no link and no directive. + /// Left to the platform, the link was made, then ended by the peer's own + /// `superseded` that overtook this device's report, and counted against + /// the peer, whose next offers were paused for nothing. + pub(crate) fn answer_superseded(&mut self, peer: &str, link_id: &str, now: Instant) { + if self.peer() == Some(peer) { + return; + } + self.remember_ended(link_id, now); + self.reply_close(peer, link_id, CloseReason::Superseded); + } + fn reply_close(&mut self, peer: &str, link: &str, reason: CloseReason) { self.frames.push_back(( peer.to_string(), @@ -2743,6 +2757,48 @@ mod tests { } } + #[test] + fn a_frame_from_a_peer_another_stream_reaches_is_answered_superseded() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + // The home-network stream proved both ends while the Android's offer + // was in flight, and the Android then superseded its own link. Twice: + // with the offer made into a link and ended by the Android's close, + // the second paused the Android's offers for ten minutes. + for seed in [1, 2] { + let id = android.request(HIGH, fresh(seed), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + let offer = android.take_frames().remove(0).1; + assert!(matches!(offer.body, FrameBody::Offer(_))); + iphone.answer_superseded(LOW, &offer.link, now); + assert!( + iphone.next_directive(now).is_none(), + "no prompt for a reached peer" + ); + assert_eq!( + iphone.take_frames()[0].1.body, + FrameBody::Close { + reason: "superseded".to_string() + } + ); + assert!(android.platform_ended(&id, CloseReason::Superseded, now)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + android.take_changes(); + iphone.take_changes(); + } + // The next unasked offer, with no other stream, is still joined. + let id = android.request(HIGH, fresh(3), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + assert_eq!( + iphone.next_directive(now).unwrap().kind, + FastLinkDirectiveKind::Join + ); + } + #[test] fn a_superseded_link_leaves_the_other_streams_transfers_alone() { let mut android = machine(host_roles()); diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index 85c5bd657..f12c48a3c 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -20,7 +20,7 @@ use tracing::{debug, warn}; use super::prefixes::internal_prefixes; use super::OfflineProtocol; use crate::fast_link::{ - CloseReason, FastLinkDirective, FastLinkRefusal, FastLinkRoles, Frame, FreshLink, + CloseReason, FastLinkDirective, FastLinkRefusal, FastLinkRoles, Frame, FrameBody, FreshLink, }; use crate::{Error, Event, Result}; @@ -180,6 +180,18 @@ impl OfflineProtocol { let Some(local) = self.local_address().map(str::to_string) else { return; }; + // A peer another stream already reaches gets no new link: that stream + // carries what the link would (`answer_superseded`). A link already + // held with it takes the frame as usual; its platform gives way. + if !matches!(frame.body, FrameBody::Close { .. }) + && self.fast_links.peer() != Some(sender) + && self.peer_stream_proves(sender) + { + self.fast_links + .answer_superseded(sender, &frame.link, Instant::now()); + self.flush_fast_link(); + return; + } self.fast_links.on_frame( sender, &local, diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 9e53e30ad..831bd3033 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -356,6 +356,44 @@ fn fast_link_frames_prefer_bluetooth_over_the_peer_stream() { assert!(bob.protocol.next_fast_link_directive().is_some()); } +/// An offer from a peer another stream already reaches is answered +/// `superseded` by the engine itself: no join prompt, and the host's link +/// ends with that reason. Left to the platform, the offer made a link that +/// the host's own `superseded` then ended, counted against the host. +#[test] +fn an_offer_to_a_peer_a_stream_already_reaches_is_answered_superseded() { + use offline_protocol_transport::PeerLink; + + let (mut alice, mut bob) = pair(); + let link_id = alice.protocol.request_fast_link(&bob.address).unwrap(); + alice.protocol.next_fast_link_directive().unwrap(); + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + let offer = alice.take_sent(); + + // The two meet over a shared LAN while the offer is in flight. + let stream = MockTransport::new(TransportType::WiFiDirect); + stream.start().unwrap(); + stream.set_connected_peers(vec![PeerLink::new(alice.address.clone())]); + bob.protocol + .transport_manager_mut() + .add_transport(TransportType::WiFiDirect, Box::new(stream.clone())); + + bob.deliver(offer); + assert!( + bob.protocol.next_fast_link_directive().is_none(), + "no join, so no prompt" + ); + assert!(bob.link_states().is_empty(), "no link was made"); + alice.deliver(bob.take_sent()); + assert_eq!( + alice.link_states().last(), + Some(&("closed".to_string(), Some("superseded".to_string()))) + ); +} + /// Blocking a peer ends its fast link at once: the platform takes the network /// down, and nothing is sent to the blocked peer. #[test] diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 5b6045b3f..3113ce55e 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -108,7 +108,8 @@ prompt, and without the pause a peer could put up another the moment one was refused. Two offers in a row that the peer made unasked and that ended having carried nothing, up or not, start the same pause, whatever the peer's reason or the offer's expiry, unless this device ended them itself (its application -closing the link, leaving the foreground): a prompt the user ignores is never +closing the link, leaving the foreground, another stream reaching the peer +first): a prompt the user ignores is never declined, and without this the peer could prompt again once per offer lifetime. One is forgiven, a link that carries something clears the count, and the user's own request to that peer ends the pause. A second offer @@ -238,7 +239,13 @@ passphrase. had just joined, and leaving the home network for it lost both 40 s later. Hence a platform that sees a stream other than the link's own prove the link's peer first ends the link `superseded` before announcing the stream, - and answers a directive for a peer a stream already reaches the same way. + and answers a directive for a peer a stream already reaches the same way; + the engine answers a `request` or `offer` from such a peer `superseded` + itself, with no link, since the peer's own `superseded` can overtake this + device's report and would count against the peer. A stream over the + group itself is the link's own however it was dialled: an Android below 13 + advertises on the group's interface, and an iPhone's general dial can + prove the host there before the link's own dial. Such an end is the platform's own and never counts against the peer, and the transfers on the slot are the other stream's, so none is failed. - **A joiner that falls silent** when iOS takes the network away leaves the From f1ed7b39e4a43ca080cacc5cb75103775cb0cf1f Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 18:19:58 +0530 Subject: [PATCH 79/81] fix(protocol): a peer's superseded is not counted, and a stream proved before dhcp stays the link's when both phones held a pending link and the peer's superseded close overtook this device's own report, it counted against the peer; with another stream reaching the peer it is now this device's own end. a peer's superseded for a link up here is any close, and releases its transfers. a join the platform has not taken gives way in the engine when a stream proves the peer. on ios, once joined, only a stream whose path has a gateway that is not the host supersedes the link: the bonjour stream over the group proves over a link-local address before dhcp, with no gateway, and was ended with the group it ran on. android lets a parked join give way too. --- .../com/offlineprotocol/WifiDirectManager.kt | 6 +- .../react-native/ios/WifiDirectManager.swift | 19 ++- crates/offline-protocol-uniffi/src/lib.rs | 20 ++- crates/offline-protocol/src/fast_link.rs | 135 ++++++++++++++++-- .../src/protocol/fast_link.rs | 15 ++ .../src/protocol/tests/fast_link.rs | 45 ++++++ docs/state-machines/fast-link.md | 15 +- 7 files changed, 235 insertions(+), 20 deletions(-) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index ed4c04ee8..5e599ee98 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1483,8 +1483,9 @@ class WifiDirectManager( // asynchronous, so a join that follows a close in one drain finds the // device still in that group. private var fastLinkLeaving = false - // A join waiting for [fastLinkLeaving] to clear (transport thread). - private var parkedFastLinkJoin: FastLinkDirective? = null + // A join waiting for [fastLinkLeaving] to clear (written on the transport + // thread; read on a socket thread by [supersedeFastLinkFor]). + @Volatile private var parkedFastLinkJoin: FastLinkDirective? = null // The name of a fast-link group closed before it came up (transport // thread). Its removeGroup can lose to the negotiation, answered BUSY, and // the group then appears with nothing tracking it; seen, it is removed. @@ -1566,6 +1567,7 @@ class WifiDirectManager( if (sockets.carrierOf(address) != PeerStreamSockets.Carrier.LAN) return val linkId = fastLinkHosted?.takeIf { it.peer == address }?.linkId ?: fastLinkJoined?.takeIf { it.peer == address }?.linkId + ?: parkedFastLinkJoin?.takeIf { it.peerId == address }?.linkId ?: return emitDiagnostic("info", "Fast link: another stream reached the peer first", mapOf( "linkId" to linkId, diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index c5f6e46f3..1cf7c6dea 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -831,12 +831,14 @@ extension WifiDirectManager: PeerStreamHost { // holds the address, never does. if let pending = fastLink, pending.peer == address, let held = peers.handle(for: address), held !== (pending.stream as? Stream) { - if pending.joined, let path = held.connection.currentPath, - Self.isGateway(pending.host, of: path) { + if pending.joined && !Self.runsOffTheGroup(held, host: pending.host) { // Over the group itself, from the general Bonjour dial: an // Android below 13 advertises on the group's interface too, // and that dial needs no DHCP address, so it can prove the - // host before the link's own. It is the link's stream. + // host before the link's own, over a link-local address with + // no gateway on its path yet. It is the link's stream, and + // the link's own dial, if any, is let go. + if let own = pending.stream as? Stream { own.connection.cancel() } pending.stream = held } else { emitDiagnostic("info", "Fast link: another stream reached the peer first", context: [ @@ -1139,6 +1141,17 @@ extension WifiDirectManager { } } + /// Whether `stream` positively runs over a network other than the + /// group: its path has a gateway, and none is the offered host. That is + /// a phone the join left on its own Wi-Fi. A path with no gateway yet is + /// a link-local one on the group before DHCP, and counts as on it. + private static func runsOffTheGroup(_ stream: Stream, host: String) -> Bool { + guard let path = stream.connection.currentPath, !path.gateways.isEmpty else { + return false + } + return !isGateway(host, of: path) + } + /// Whether `host`, an IP literal, is a gateway of `path`. private static func isGateway(_ host: String, of path: NWPath) -> Bool { let v4 = IPv4Address(host) diff --git a/crates/offline-protocol-uniffi/src/lib.rs b/crates/offline-protocol-uniffi/src/lib.rs index 990c5815f..caff99914 100644 --- a/crates/offline-protocol-uniffi/src/lib.rs +++ b/crates/offline-protocol-uniffi/src/lib.rs @@ -20483,7 +20483,10 @@ mod tests { /// `react_native_wifi_direct_announces_only_proved_addresses`) hold the /// order, the end before the announcement; this holds the conditions /// and the directive-time refusals. A stream over the group itself is - /// the link's own however it was dialled. + /// the link's own however it was dialled, including one proved over a + /// link-local address before DHCP, whose path has no gateway yet: only a + /// path whose gateway is positively not the host supersedes after the + /// join. #[test] fn a_pending_fast_link_gives_way_to_a_stream_that_reached_the_peer_first() { let kotlin = @@ -20493,9 +20496,12 @@ mod tests { swift.contains( "if let pending = fastLink, pending.peer == address, \ let held = peers.handle(for: address), held !== (pending.stream as? Stream) { \ - if pending.joined, let path = held.connection.currentPath, \ - Self.isGateway(pending.host, of: path) { pending.stream = held } else {" - ), + if pending.joined && !Self.runsOffTheGroup(held, host: pending.host) {" + ) && swift.contains("pending.stream = held } else {") + && swift.contains( + "guard let path = stream.connection.currentPath, !path.gateways.isEmpty else { \ + return false } return !isGateway(host, of: path)" + ), "ios/WifiDirectManager.swift: a stream that is not the link's own must end a \ pending link for its peer, and one over the group itself (its path's gateway \ the offered host) is the link's own: an Android below 13 advertises on the \ @@ -20518,6 +20524,12 @@ mod tests { "WifiDirectManager.kt: only a LAN stream supersedes a pending link; a P2P one is \ the link's own" ); + assert!( + kotlin.contains( + "?: parkedFastLinkJoin?.takeIf { it.peerId == address }?.linkId ?: return" + ), + "WifiDirectManager.kt: a parked tie-break join gives way like any pending link" + ); for directive in ["hostFastLink", "joinFastLink"] { assert!( kotlin.contains(&format!( diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index f61e5b3cd..cde237823 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -791,6 +791,26 @@ impl FastLinks { } } + /// The peer ended a link not up here `superseded`, and another stream + /// does reach it: this device would have said the same, and its own + /// report lost the race to the peer's close. Ended as this device's own, + /// so it is not counted against the peer. False when no such link is + /// held, or it is up here (then the peer's close is taken as any other). + pub(crate) fn peer_superseded_while_reached( + &mut self, + peer: &str, + link_id: &str, + now: Instant, + ) -> bool { + if !self.link.as_ref().is_some_and(|link| { + link.peer == peer && link.id == link_id && link.state != FastLinkState::Up + }) { + return false; + } + self.end_as(CloseReason::Superseded, false, false, now); + true + } + /// A `request` or `offer` from `peer` arrived while another peer stream /// already reaches it, and this device holds no link with it: answered /// `superseded` as this device's own end, with no link and no directive. @@ -1058,9 +1078,18 @@ impl FastLinks { let Some(link) = self.link.as_mut() else { return; }; - if link.peer == peer - && matches!(link.state, FastLinkState::Offered | FastLinkState::Joining) - { + if link.peer != peer { + return; + } + // A join the platform has not taken yet has no stream of its own, so + // this one is another's (both devices on one home network): the + // link gives way, as the platform's own report would have it, rather + // than going up on a stream that is not its own. + if link.state == FastLinkState::Joining && !link.platform_engaged { + self.end(CloseReason::Superseded, true, now); + return; + } + if matches!(link.state, FastLinkState::Offered | FastLinkState::Joining) { link.state = FastLinkState::Up; link.deadline = None; link.last_activity = now; @@ -1277,6 +1306,13 @@ impl FastLinks { /// a `close` frame when the peer knows of it and `tell_peer`, and one /// change (invariant 4). fn end(&mut self, reason: CloseReason, tell_peer: bool, now: Instant) { + self.end_as(reason, tell_peer, !tell_peer, now); + } + + /// [`Self::end`], with whose end it is for counting given apart from + /// whether the peer is told: a peer's `superseded` that this device would + /// have reported itself is not the peer's to answer for. + fn end_as(&mut self, reason: CloseReason, tell_peer: bool, by_peer: bool, now: Instant) { let Some(link) = self.link.take() else { return; }; @@ -1286,13 +1322,14 @@ impl FastLinks { self.directives .retain(|pending| pending.directive.link_id != link.id); self.remember_ended(&link.id, now); - // A superseded link's peer is still reached, over the other stream, - // and a transfer there is that stream's, not the link's. - if link.state == FastLinkState::Up && reason != CloseReason::Superseded { + // A link this device superseded is still reached over the other + // stream, and a transfer there is that stream's. One the peer ended + // `superseded` while it was up here ran over its own stream. + if link.state == FastLinkState::Up && !(reason == CloseReason::Superseded && !by_peer) { self.released.push_back(link.peer.clone()); } if link.role == FastLinkRole::Host && link.requested_by_peer { - self.count_hosting(&link.peer, link.carried, !tell_peer, reason, now); + self.count_hosting(&link.peer, link.carried, by_peer, reason, now); } if link.role == FastLinkRole::Join { if self.ended_joins.len() >= MAX_ENDED_REMEMBERED { @@ -1309,7 +1346,7 @@ impl FastLinks { self.record_decline(link.peer.clone(), now); } if link.requested_by_peer { - self.count_offer(&link.peer, link.carried, !tell_peer, reason, now); + self.count_offer(&link.peer, link.carried, by_peer, reason, now); } } if link.platform_engaged { @@ -2799,6 +2836,88 @@ mod tests { ); } + #[test] + fn a_stream_proving_a_join_the_platform_has_not_taken_supersedes_it() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + let id = android.request(HIGH, fresh(1), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + iphone.take_changes(); + // The join directive waits for the platform's drain when a home + // network stream proves the host: that stream cannot be the link's. + iphone.stream_proved(LOW, now); + assert_eq!(states(&mut iphone), [FastLinkState::Closed]); + assert!( + iphone.next_directive(now).is_none(), + "the join was withdrawn" + ); + assert_eq!( + iphone.take_frames()[0].1.body, + FrameBody::Close { + reason: "superseded".to_string() + } + ); + } + + #[test] + fn a_peers_superseded_that_overtook_this_devices_report_is_not_counted() { + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let now = Instant::now(); + // The iPhone asks; both platforms then see a home-network stream and + // each ends the link `superseded`, the iPhone's close reaching the + // Android before its own platform's report. + let ask = |android: &mut FastLinks, iphone: &mut FastLinks, seed| { + // The last link's close for each platform, which drops its group. + while android.next_directive(now).is_some() {} + while iphone.next_directive(now).is_some() {} + let id = iphone.request(LOW, fresh(seed), now).unwrap(); + deliver(iphone, HIGH, android, LOW, now, 0); + let host = android.next_directive(now)?; + assert!(android.hosting(&host.link_id, "192.168.49.1", 8988, now, 0)); + deliver(android, LOW, iphone, HIGH, now, 0); + iphone.next_directive(now); + assert!(iphone.platform_ended(&id, CloseReason::Superseded, now)); + Some(id) + }; + for seed in [1, 2] { + let id = ask(&mut android, &mut iphone, seed).unwrap(); + iphone.take_frames(); + assert!(android.peer_superseded_while_reached(HIGH, &id, now)); + // The Android's own report then finds the link gone. + assert!(!android.platform_ended(&id, CloseReason::Superseded, now)); + } + assert!( + ask(&mut android, &mut iphone, 3).is_some(), + "two meetings over the home network are not two misses" + ); + iphone.take_frames(); + android.take_frames(); + + // Taken as an ordinary close, the same two put the Android in backoff. + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + for seed in [1, 2] { + ask(&mut android, &mut iphone, seed).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + } + assert!(ask(&mut android, &mut iphone, 3).is_none()); + + // Up here, the peer's `superseded` is any close: the link's own + // stream carried it, and its transfers are released. + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + let id = android.request(HIGH, fresh(9), now).unwrap(); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + android.stream_proved(HIGH, now); + assert!(!android.peer_superseded_while_reached(HIGH, &id, now)); + let _ = &mut iphone; + } + #[test] fn a_superseded_link_leaves_the_other_streams_transfers_alone() { let mut android = machine(host_roles()); diff --git a/crates/offline-protocol/src/protocol/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs index f12c48a3c..a29718901 100644 --- a/crates/offline-protocol/src/protocol/fast_link.rs +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -180,6 +180,21 @@ impl OfflineProtocol { let Some(local) = self.local_address().map(str::to_string) else { return; }; + // The peer's `superseded` for a link not up here, with another stream + // reaching it, is the end this device would have reported itself. + if let FrameBody::Close { reason } = &frame.body { + if CloseReason::parse(reason) == CloseReason::Superseded + && self.peer_stream_proves(sender) + && self.fast_links.peer_superseded_while_reached( + sender, + &frame.link, + Instant::now(), + ) + { + self.flush_fast_link(); + return; + } + } // A peer another stream already reaches gets no new link: that stream // carries what the link would (`answer_superseded`). A link already // held with it takes the frame as usual; its platform gives way. diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index 831bd3033..dfbbc075a 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -394,6 +394,51 @@ fn an_offer_to_a_peer_a_stream_already_reaches_is_answered_superseded() { ); } +/// Two phones that meet over a shared LAN while a link they both hold is +/// pending each end it `superseded`. The joiner's close reaching the host +/// before the host's own report is not a miss: two such meetings left the +/// host in backoff against the joiner. +#[test] +fn a_peers_superseded_with_a_stream_reaching_it_is_not_counted() { + use offline_protocol_transport::PeerLink; + + let (mut alice, mut bob) = pair(); + let stream = MockTransport::new(TransportType::WiFiDirect); + stream.start().unwrap(); + alice + .protocol + .transport_manager_mut() + .add_transport(TransportType::WiFiDirect, Box::new(stream.clone())); + for _ in 0..2 { + let link_id = bob.protocol.request_fast_link(&alice.address).unwrap(); + alice.deliver(bob.take_sent()); + while let Some(directive) = alice.protocol.next_fast_link_directive() { + if directive.kind == FastLinkDirectiveKind::Host { + alice + .protocol + .fast_link_hosting(&link_id, "192.168.49.1", 8988) + .unwrap(); + } + } + bob.deliver(alice.take_sent()); + bob.protocol.next_fast_link_directive().unwrap(); + // The LAN stream comes up; bob's platform reports first. + stream.set_connected_peers(vec![PeerLink::new(bob.address.clone())]); + bob.protocol.fast_link_ended(&link_id, "superseded"); + alice.deliver(bob.take_sent()); + assert_eq!( + alice.link_states().last(), + Some(&("closed".to_string(), Some("superseded".to_string()))) + ); + stream.set_connected_peers(vec![]); + } + bob.protocol.request_fast_link(&alice.address).unwrap(); + alice.deliver(bob.take_sent()); + let hosted = std::iter::from_fn(|| alice.protocol.next_fast_link_directive()) + .any(|directive| directive.kind == FastLinkDirectiveKind::Host); + assert!(hosted, "the third request is hosted, not answered busy"); +} + /// Blocking a peer ends its fast link at once: the platform takes the network /// down, and nothing is sent to the blocked peer. #[test] diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 3113ce55e..2f9793dbf 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -245,9 +245,18 @@ passphrase. device's report and would count against the peer. A stream over the group itself is the link's own however it was dialled: an Android below 13 advertises on the group's interface, and an iPhone's general dial can - prove the host there before the link's own dial. - Such an end is the platform's own and never counts against the peer, and - the transfers on the slot are the other stream's, so none is failed. + prove the host there before the link's own dial, over a link-local + address before DHCP, so once the iPhone has joined only a stream whose path + has a gateway that is not the host gives way. + Such an end is the platform's own and never counts against the peer, nor + does the peer's own `superseded` for a link not yet up here while another + stream reaches the peer (its close can overtake this device's report; + counted, two meetings on a home network paused the peer). A peer's + `superseded` for a link up here is any close: the link's own stream + carried it. The engine also ends a join its platform has not yet taken + `superseded` when a stream proves the peer, since such a link has no + stream of its own. A link this device superseded fails no transfer on the + slot: the transfers there are the other stream's. - **A joiner that falls silent** when iOS takes the network away leaves the host's stream half open until keepalive ends it. Hence the platform's report. From 05ff587c7c01be9c05436ce4be78d1404ba845f8 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 18:28:47 +0530 Subject: [PATCH 80/81] fix(protocol): a host whose offer is not out gives way to a stream, and the superseded guard says what it covers a stream that proves the peer while the host's group is still coming up cannot be the link's own, so the link now ends superseded before any offer is sent. the guard for a peer's superseded covers a stream this device has already proved but its platform did not recognise; one that arrives before this device proves the stream at all is still counted, and the docs, the comment and the test names now say so. the test also checks a peer's superseded for an up link releases its transfers and is counted. --- crates/offline-protocol/src/fast_link.rs | 78 +++++++++++++++---- .../src/protocol/tests/fast_link.rs | 7 +- docs/state-machines/fast-link.md | 18 +++-- 3 files changed, 77 insertions(+), 26 deletions(-) diff --git a/crates/offline-protocol/src/fast_link.rs b/crates/offline-protocol/src/fast_link.rs index cde237823..4bd1fdfa0 100644 --- a/crates/offline-protocol/src/fast_link.rs +++ b/crates/offline-protocol/src/fast_link.rs @@ -792,10 +792,15 @@ impl FastLinks { } /// The peer ended a link not up here `superseded`, and another stream - /// does reach it: this device would have said the same, and its own - /// report lost the race to the peer's close. Ended as this device's own, - /// so it is not counted against the peer. False when no such link is - /// held, or it is up here (then the peer's close is taken as any other). + /// already reaches it here: this device would have said the same, but + /// its platform did not recognise that stream as another's (it was + /// announced before the link was published to the platform, say). Ended + /// as this device's own, so it is not counted against the peer. False + /// when no such link is held, or it is up here (then the peer's close is + /// taken as any other). A peer's `superseded` that arrives before this + /// device has proved the stream at all is counted: telling it from a + /// peer dodging the limits would need a wait, and it needs a Bluetooth + /// frame to beat the stream's own preamble. pub(crate) fn peer_superseded_while_reached( &mut self, peer: &str, @@ -1085,7 +1090,10 @@ impl FastLinks { // this one is another's (both devices on one home network): the // link gives way, as the platform's own report would have it, rather // than going up on a stream that is not its own. - if link.state == FastLinkState::Joining && !link.platform_engaged { + // Nor has a host whose offer is not out yet. + if link.state == FastLinkState::Hosting + || (link.state == FastLinkState::Joining && !link.platform_engaged) + { self.end(CloseReason::Superseded, true, now); return; } @@ -2863,13 +2871,38 @@ mod tests { } #[test] - fn a_peers_superseded_that_overtook_this_devices_report_is_not_counted() { + fn a_stream_proving_the_peer_before_the_offer_is_out_supersedes_the_link() { + let mut android = machine(host_roles()); + let now = Instant::now(); + let id = android.request(HIGH, fresh(1), now).unwrap(); + assert_eq!( + android.next_directive(now).unwrap().kind, + FastLinkDirectiveKind::Host + ); + android.take_changes(); + // The group is still coming up when a home-network stream proves the + // peer: no offer, and the platform is told to drop the group. + android.stream_proved(HIGH, now); + assert_eq!(states(&mut android), [FastLinkState::Closed]); + assert_eq!( + android.next_directive(now).unwrap().kind, + FastLinkDirectiveKind::Close + ); + assert!(!android.hosting(&id, "192.168.49.1", 8988, now, 0)); + assert!(android + .take_frames() + .iter() + .all(|(_, frame)| !matches!(frame.body, FrameBody::Offer(_)))); + } + + #[test] + fn a_peers_superseded_for_a_link_a_stream_already_reaches_is_not_counted() { let mut android = machine(host_roles()); let mut iphone = machine(join_roles()); let now = Instant::now(); - // The iPhone asks; both platforms then see a home-network stream and - // each ends the link `superseded`, the iPhone's close reaching the - // Android before its own platform's report. + // The iPhone asks; a home-network stream reaches both, the iPhone's + // platform ends the link `superseded`, and the Android's platform + // announced the stream without recognising it as another's. let ask = |android: &mut FastLinks, iphone: &mut FastLinks, seed| { // The last link's close for each platform, which drops its group. while android.next_directive(now).is_some() {} @@ -2907,15 +2940,28 @@ mod tests { assert!(ask(&mut android, &mut iphone, 3).is_none()); // Up here, the peer's `superseded` is any close: the link's own - // stream carried it, and its transfers are released. + // stream carried it, so its transfers are released and, carrying + // nothing, it is counted. let mut android = machine(host_roles()); let mut iphone = machine(join_roles()); - let id = android.request(HIGH, fresh(9), now).unwrap(); - android.next_directive(now); - assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); - android.stream_proved(HIGH, now); - assert!(!android.peer_superseded_while_reached(HIGH, &id, now)); - let _ = &mut iphone; + for seed in [7, 8] { + while android.next_directive(now).is_some() {} + let id = iphone.request(LOW, fresh(seed), now).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + android.next_directive(now); + assert!(android.hosting(&id, "192.168.49.1", 8988, now, 0)); + deliver(&mut android, LOW, &mut iphone, HIGH, now, 0); + iphone.next_directive(now); + android.stream_proved(HIGH, now); + assert!(!android.peer_superseded_while_reached(HIGH, &id, now)); + assert!(iphone.platform_ended(&id, CloseReason::Superseded, now)); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + assert_eq!(android.take_released(), [HIGH.to_string()]); + } + while android.next_directive(now).is_some() {} + iphone.request(LOW, fresh(9), now).unwrap(); + deliver(&mut iphone, HIGH, &mut android, LOW, now, 0); + assert!(android.next_directive(now).is_none(), "two misses: busy"); } #[test] diff --git a/crates/offline-protocol/src/protocol/tests/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs index dfbbc075a..79f1fc65e 100644 --- a/crates/offline-protocol/src/protocol/tests/fast_link.rs +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -395,9 +395,10 @@ fn an_offer_to_a_peer_a_stream_already_reaches_is_answered_superseded() { } /// Two phones that meet over a shared LAN while a link they both hold is -/// pending each end it `superseded`. The joiner's close reaching the host -/// before the host's own report is not a miss: two such meetings left the -/// host in backoff against the joiner. +/// pending: the joiner ends it `superseded`, and the host already knows the +/// stream but its platform did not recognise it as another's. The joiner's +/// close is then the host's own end, not a miss: counted, two such meetings +/// left the host in backoff against the joiner. #[test] fn a_peers_superseded_with_a_stream_reaching_it_is_not_counted() { use offline_protocol_transport::PeerLink; diff --git a/docs/state-machines/fast-link.md b/docs/state-machines/fast-link.md index 2f9793dbf..8df682292 100644 --- a/docs/state-machines/fast-link.md +++ b/docs/state-machines/fast-link.md @@ -249,13 +249,17 @@ passphrase. address before DHCP, so once the iPhone has joined only a stream whose path has a gateway that is not the host gives way. Such an end is the platform's own and never counts against the peer, nor - does the peer's own `superseded` for a link not yet up here while another - stream reaches the peer (its close can overtake this device's report; - counted, two meetings on a home network paused the peer). A peer's - `superseded` for a link up here is any close: the link's own stream - carried it. The engine also ends a join its platform has not yet taken - `superseded` when a stream proves the peer, since such a link has no - stream of its own. A link this device superseded fails no transfer on the + does the peer's own `superseded` for a link not yet up here while a stream + this device already proved reaches the peer (its platform did not + recognise that stream as another's; counted, two meetings on a home + network paused the peer). A peer's `superseded` that arrives before this + device has proved the stream at all is counted: telling it from a peer + dodging the limits would need a wait, and it needs a Bluetooth frame to + beat the stream's own preamble. A peer's `superseded` for a link up here + is any close: the link's own stream carried it. The engine also ends a + join its platform has not yet taken, or a link whose host has not yet sent + its offer, `superseded` when a stream proves the peer, since such a link + has no stream of its own. A link this device superseded fails no transfer on the slot: the transfers there are the other stream's. - **A joiner that falls silent** when iOS takes the network away leaves the host's stream half open until keepalive ends it. Hence the platform's From 341ba457e18a2686a92a5bb2615ddb6606700788 Mon Sep 17 00:00:00 2001 From: Mizan Ali Date: Tue, 17 Nov 2026 18:49:22 +0530 Subject: [PATCH 81/81] fix(bindings): register fast_link_changed with the event parser, and gate the named group on api 29 for lint main's typescript event parser keeps a list of every event tag, and its guard refused the branch's new one. android lint refused the named-group createGroup call below api 29; the fast link was already off there at runtime, and the check now sits where the call is made. --- .../src/main/java/com/offlineprotocol/WifiDirectManager.kt | 6 ++++++ bindings/react-native/src/parseProtocolEvent.ts | 1 + 2 files changed, 7 insertions(+) diff --git a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index 5e599ee98..5d21bb387 100644 --- a/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt +++ b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt @@ -1601,6 +1601,12 @@ class WifiDirectManager( fastLinkEnded(directive.linkId, "superseded") return } + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + // A named group needs Android 10, and [fastLinkSupported] declares + // no host role below it; this says so where the call is made. + fastLinkEnded(directive.linkId, "host_failed") + return + } val ssid = directive.ssid val passphrase = directive.passphrase val p2p = wifiP2pManager diff --git a/bindings/react-native/src/parseProtocolEvent.ts b/bindings/react-native/src/parseProtocolEvent.ts index 863439df0..8cdebf730 100644 --- a/bindings/react-native/src/parseProtocolEvent.ts +++ b/bindings/react-native/src/parseProtocolEvent.ts @@ -38,6 +38,7 @@ export const PROTOCOL_EVENT_TYPES = [ 'dors_score_updated', 'dors_transport_selected', 'dors_transport_switched', + 'fast_link_changed', 'file_progress', 'file_receive_failed', 'file_received',