diff --git a/CHANGELOG.md b/CHANGELOG.md index c60c65211..01d490cf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,28 @@ 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`, 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 + 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.** `OfflineProtocolReferenceStorage` opens the Keychain or Keystore MLS store and the app-container protocol-state store for one `(appId, profile)` account, @@ -76,6 +98,15 @@ 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 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 - **Flutter on Android now reports a lost MLS identity.** Its engine host 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/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..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// 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 befee7ac4..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// 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 9015eadf1..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// 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 b52a91da6..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // 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..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // 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..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // 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..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 = 3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799 +// UDL_SHA256 = d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80 // Do not edit. #nullable enable 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/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..6b7557dd3 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) 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)) { 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..42c528365 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, boolean acceptUnrequested) { + 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), FfiConverterBoolean.INSTANCE.lower(acceptUnrequested), _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..cae72bcca 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, 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 dc81951fc..963c502ee 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.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, 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, acceptUnrequested, _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..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 = "3e28d977491b82d3b713c1fc274811e6f066a02f4f98dab6d1ede6512fd9a799" +UDL_SHA256 = "d9a4bfe9da239313288180f511cab1c80981f1b6db53f2ba9a90b73c838e6a80" 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,26 @@ ('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'), + ('accept_unrequested', + 'boolean')), + 'void'), 'wifi_direct_status_changed': ((('is_connected', 'boolean'),), 'void')}, 'namespace': {'derive_address': ((('public_key', 'sequence'),), 'string'), @@ -638,6 +653,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..6744d05a4 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() != 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") 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,14 @@ 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.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 +4435,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 +4786,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 +7831,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 +11172,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 +11236,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 +11456,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 +11562,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,accept_unrequested: bool) -> None: + raise NotImplementedError def wifi_direct_status_changed(self, is_connected: bool) -> None: raise NotImplementedError @@ -11676,6 +11886,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 +13491,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 +14379,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 +14448,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 +14490,27 @@ 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,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 + _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 +14641,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/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..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 @@ -168,9 +168,20 @@ 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 + /** 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 } @@ -276,6 +287,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..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()) @@ -410,6 +414,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..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 @@ -98,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)) @@ -524,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/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt b/bindings/react-native/android/src/main/java/com/offlineprotocol/WifiDirectManager.kt index aaaa86c8b..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 @@ -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.* @@ -89,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. @@ -143,6 +146,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 } /** @@ -154,6 +160,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? = @@ -200,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() }) @@ -513,6 +528,13 @@ class WifiDirectManager( // Start server socket on the port bound above. startServerSocket(listener) + // 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) // Notify protocol. Wi-Fi P2P off at start arrives next as the @@ -569,8 +591,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) } } } @@ -595,6 +639,8 @@ class WifiDirectManager( // Stop server socket stopServerSocket() + endFastLinkOnStop() + lan?.stop() lan = null @@ -906,7 +952,9 @@ class WifiDirectManager( "groupOwnerAddress" to (groupOwnerAddress ?: "null") )) + if (isGroupOwner) fastLinkGroupChanged() if (!isGroupOwner && groupOwnerAddress != null) { + fastLinkJoined?.connected = true // Connect to group owner connectToGroupOwner(groupOwnerAddress!!) } @@ -924,6 +972,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 @@ -1110,6 +1160,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 } @@ -1403,6 +1456,405 @@ 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, + // 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 + } + + // 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 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 (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. + private var orphanedFastLinkSsid: String? = 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 && fastLinkMode != FastLinkMode.OFF + try { + protocol.wifiDirectSetFastLinkRoles(able, able, fastLinkMode == FastLinkMode.ANY) + } 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. 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() { + 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 + // One directive never takes the process down: everything below + // runs on the transport looper, where an exception is a crash. + try { + 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( + "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") + } + } + } + + /** + * 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 + ?: parkedFastLinkJoin?.takeIf { it.peerId == 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) + } catch (e: Exception) { + Log.w(TAG, "Could not report a fast-link end", e) + } + } + + 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 + * 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) { + 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 + } + 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 + 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 + 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() {} + 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), + )) + 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) { + 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 + 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 && ssid != null && passphrase != null && fastLinkSupported) { + // An offer whose network Android cannot join by name. + 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 + ) { + fastLinkEnded(directive.linkId, "failed") + return + } + 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 { + 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) { + // 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 && p2p != null && ch != null + if (!hosted.reported) orphanedFastLinkSsid = hosted.ssid + if (p2p != null && ch != null) p2p.removeGroup(ch, quietListener("remove fast-link group")) + } + if (joined?.linkId == linkId) { + fastLinkJoined = null + 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")) + } + } + } + + /** + * 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 + if (hosted == null) { + removeOrphanedFastLinkGroup() + 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 + // 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) { + 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) + } + } + } + + /** + * 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() { + 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 + // 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 { + joinFastLink(parked) + } catch (e: Exception) { + fastLinkEnded(parked.linkId, "failed") + } + } + 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, + * 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 + val joined = fastLinkJoined + val parked = parkedFastLinkJoin + fastLinkHosted = null + fastLinkJoined = null + parkedFastLinkJoin = null + fastLinkLeaving = false + orphanedFastLinkSsid = null + 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, "closed") } + joined?.let { fastLinkEnded(it.linkId, "closed") } + try { + protocol.wifiDirectSetFastLinkRoles(false, false, false) + } catch (_: Exception) {} + } + // MARK: - Socket Operations private fun startServerSocket(listener: PeerStreamListener.Bound) { @@ -1483,10 +1935,20 @@ class WifiDirectManager( socketExecutor.execute { var ran = PeerStreamSockets.Ran(proved = null, heard = false) try { + // 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(address, PeerStreamListener.GROUP_OWNER_PORT), + InetSocketAddress( + address, + joined?.port ?: PeerStreamListener.GROUP_OWNER_PORT, + ), CONNECTION_TIMEOUT_MS.toInt(), ) } catch (e: Exception) { @@ -1500,10 +1962,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) @@ -1727,6 +2193,7 @@ class WifiDirectManager( } private fun pollAndSendMessages() { + drainFastLinkDirectives() if (state != TransportState.RUNNING || sockets.isEmpty()) return try { @@ -1882,3 +2349,52 @@ 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, 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? { + 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 + } + } +} + +/** + * `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 aaaaac5fe..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 @@ -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,`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 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) != 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) { 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, `acceptUnrequested`: 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,21 @@ open class OfflineProtocol: Disposable, AutoCloseable, OfflineProtocolInterface + override fun `wifiDirectSetFastLinkRoles`(`canHost`: kotlin.Boolean, `canJoin`: kotlin.Boolean, `acceptUnrequested`: 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`), + FfiConverterBoolean.lower(`acceptUnrequested`),_status) +} + } + + + @Throws(ProtocolException::class)override fun `wifiDirectStatusChanged`(`isConnected`: kotlin.Boolean) = @@ -8352,6 +8493,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 +12602,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 +12954,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/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)) + } +} 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/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/Generated/offline_protocol.swift b/bindings/react-native/ios/Generated/offline_protocol.swift index 65ad61aad..4fbf44088 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, acceptUnrequested: 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,17 @@ open func wifiDirectPeerDisconnected(peerId: String)throws {try rustCallWithEr } } +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), + FfiConverterBool.lower(acceptUnrequested),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 +4468,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 +10355,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 +10619,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 +11576,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 +11906,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 +12065,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() != 62518) { + 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..498f95840 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, int8_t accept_unrequested, 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/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/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/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..87fc4b516 100644 --- a/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift +++ b/bindings/react-native/ios/ProtocolEngineHostBridgeReactNative.swift @@ -93,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]) @@ -519,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]) diff --git a/bindings/react-native/ios/WifiDirectManager.swift b/bindings/react-native/ios/WifiDirectManager.swift index baa93afb0..1cf7c6dea 100644 --- a/bindings/react-native/ios/WifiDirectManager.swift +++ b/bindings/react-native/ios/WifiDirectManager.swift @@ -10,6 +10,12 @@ import Foundation import Network +// 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 enum NetworkExtension.NEHotspotConfigurationError +import let NetworkExtension.NEHotspotConfigurationErrorDomain /// The engine's peer-stream slot on iOS, over `NWListener`, `NWBrowser` and /// `NWConnection`. @@ -165,6 +171,11 @@ 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? + /// `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 @@ -285,6 +296,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), as far + // as the application's `wifiDirect.fastLink` allows. + try? protocolInstance.wifiDirectSetFastLinkRoles( + canHost: false, + canJoin: fastLinkMode != .off, + acceptUnrequested: fastLinkMode == .any + ) } public func stop() { @@ -309,6 +327,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. @@ -330,7 +355,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() { @@ -351,6 +383,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() } @@ -786,6 +821,32 @@ 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. 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, + let held = peers.handle(for: address), held !== (pending.stream as? Stream) { + 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, 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: [ + "linkId": pending.linkId, + ]) + endFastLink(reason: "superseded") + } + } do { try protocolInstance.wifiDirectPeerConnected(peerId: address) } catch { @@ -825,3 +886,355 @@ extension WifiDirectManager: PeerStreamHost { } extension WifiDirectManager: @unchecked Sendable {} + +// 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 + /// 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? + + 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 { + /// 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 + /// 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 + /// 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 { + 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() { + 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) + 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") + } + } + } + + 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 + ) + // 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) + } + + /// 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: 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. + 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 Self.isHotspotError(error, .userDenied) { + protocolInstance.wifiDirectFastLinkEnded(linkId: link.linkId, reason: "declined") + } + return + } + 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, + "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 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, + // 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; + // `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. + lookAtWifiPath { [weak self] path in + 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) + } + } + } + + /// 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) + 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 + } + } + } + + /// 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 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) + 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) + } + } +} + +/// `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 { + // 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 + default: return .off + } + } +} diff --git a/bindings/react-native/src/index.ts b/bindings/react-native/src/index.ts index 6e3e571fb..27ea22ea4 100644 --- a/bindings/react-native/src/index.ts +++ b/bindings/react-native/src/index.ts @@ -4618,6 +4618,47 @@ 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. 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. 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 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 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/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', diff --git a/bindings/react-native/src/types.ts b/bindings/react-native/src/types.ts index 71297ccfa..20bdc451b 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. @@ -1469,6 +1483,34 @@ 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`, `superseded` (another connection reached the peer first + * and carries its traffic), and others; an unknown value means it failed. + */ + reason: string | null; +} + /** * Relay promoted event */ @@ -3156,6 +3198,7 @@ export type ProtocolEvent = | MessageFailedEvent | MessageDecryptionFailedEvent | TransportSwitchedEvent + | FastLinkChangedEvent | RelayPromotedEvent | RelayDemotedEvent | RelayDemotedBatteryEvent diff --git a/bindings/ruby/lib/offline_protocol.rb b/bindings/ruby/lib/offline_protocol.rb index 248665528..b726f32bc 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, :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,16 @@ 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, accept_unrequested) + can_host = can_host ? true : false + + can_join = can_join ? true : false + + 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) is_connected = is_connected ? true : false 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/src/prefixes.rs b/crates/offline-protocol-sealed/src/prefixes.rs index 69fe5aedc..d56b0039e 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,19 @@ 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: 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)] mod tests { use super::*; @@ -90,6 +104,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 +124,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-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-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-uniffi/src/capi/generated.rs b/crates/offline-protocol-uniffi/src/capi/generated.rs index 46971573f..82cab120a 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,34 @@ 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")?; + let arg_accept_unrequested = args.take("accept_unrequested")?; + args.finish()?; + 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" => { + 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 f8c555467..1034e7b77 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, data.len()); 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,62 @@ 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, + accept_unrequested: bool, + ) { + if let Ok(mut guard) = self.lock_inner() { + guard.set_fast_link_roles(can_host, can_join, accept_unrequested); + } + } + + /// 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()?; @@ -19780,7 +19898,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", @@ -19794,6 +19914,7 @@ mod tests { "setServiceTopicCheckpoint", "subscribeService", "unsubscribeService", + "requestFastLink", ]; let mut expected: Vec<&str> = MAPPED_BEFORE_THE_SHARED_BRIDGE .iter() @@ -20115,17 +20236,358 @@ 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 + /// 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:?}" + ); + } + } + } + + /// 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. + /// 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. + #[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) { 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 { \ + 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" + ); + 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" + ); + 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" + ); + } + /// 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. A stream over the group itself is + /// 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 = + 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, \ + let held = peers.handle(for: address), held !== (pending.stream as? Stream) { \ + 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 \ + group's interface, and superseding that stream tore down the group it ran on" + ); + 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" + ); + 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!( + "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 + /// 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 = + 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" + ); + 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] fn react_native_android_wifi_direct_callback_does_not_wait_for_a_manager() { 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", @@ -21039,7 +21501,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 @@ -21055,9 +21520,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"); @@ -21289,7 +21757,7 @@ mod tests { [ ( "wifiDirectPeerConnected(", - "func peerStreamConnected(_ address: String) { do { \ + "endFastLink(reason: \"superseded\") } } do { \ try protocolInstance.wifiDirectPeerConnected(peerId: address)", ), ( @@ -21341,8 +21809,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 1e317ccab..777d9e208 100644 --- a/crates/offline-protocol-uniffi/src/offline_protocol.udl +++ b/crates/offline-protocol-uniffi/src/offline_protocol.udl @@ -1414,6 +1414,28 @@ 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 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 + // 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 +1486,42 @@ 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. `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: + // `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`, + // `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), `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); + // Reticulum transport callback (event-driven sending) void set_reticulum_transport_callback(ReticulumTransportCallback callback); @@ -2577,6 +2635,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/crates/offline-protocol/src/constants.rs b/crates/offline-protocol/src/constants.rs index 0c5875c75..a3c620d3f 100644 --- a/crates/offline-protocol/src/constants.rs +++ b/crates/offline-protocol/src/constants.rs @@ -128,6 +128,29 @@ pub const MEDIA_WINDOW_SIZE_INTERNET: usize = 8; /// Default maximum chunks in flight for media transfers. pub const DEFAULT_MEDIA_WINDOW_SIZE: usize = 4; +/// Chunk size for media transfers on the peer-stream slot (a Wi-Fi Direct +/// group, a LAN, AWDL or a fast link): 64 KiB. +/// +/// 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. pub const MAX_MEDIA_OUTBOX_ENTRIES: usize = 100; @@ -153,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/events.rs b/crates/offline-protocol/src/events.rs index 7c3366bad..4e8f89573 100644 --- a/crates/offline-protocol/src/events.rs +++ b/crates/offline-protocol/src/events.rs @@ -761,6 +761,31 @@ 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. 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 { + /// 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 +2196,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 +3069,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 +3354,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 +4646,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..4bd1fdfa0 --- /dev/null +++ b/crates/offline-protocol/src/fast_link.rs @@ -0,0 +1,3241 @@ +//! 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 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`]: 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; + +/// 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; + +/// 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 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); + +/// 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; + +/// 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, 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. +#[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, + /// 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 { + /// 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", + Self::Superseded => "superseded", + } + } + + /// 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, + "superseded" => Self::Superseded, + _ => 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, + /// 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 { + // 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) + .field("re", &self.re) + .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 { + // 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; + // 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); + 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 + } +} + +/// 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 { + /// 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, +} + +/// 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, + 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, + /// 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 + /// `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, + /// 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). +#[derive(Debug, Default)] +pub(crate) struct FastLinks { + roles: FastLinkRoles, + link: Option, + 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)>, + /// 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)>, + /// Per peer, the links hosted in a row for its requests that expired + /// with no stream from it. + 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 + /// 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, 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 { + 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) + }; + } + // 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_offers + .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); + 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, + requested_by_peer: false, + carried: false, + }); + 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(Credentials(fresh.ssid, fresh.passphrase)), + offer: None, + platform_engaged: false, + peer_engaged, + requested_by_peer: peer_engaged, + carried: false, + }); + 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, now); + return false; + } + let Some(link) = self.link.as_mut() else { + return false; + }; + let Some(Credentials(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, + re: None, + }; + 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, + ) { + // 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 = 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, + }; + // 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(_)) { + 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), + 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, 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); + } + } + } + } + + /// The peer ended a link not up here `superseded`, and another stream + /// 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, + 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. + /// 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(), + 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(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; + } + // 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)); + } + // 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; + } + 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 + .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(), + ..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; + } + 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; + } + // 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; + 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 => { + // 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. + // 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; + } + // 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, now); + } + 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 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. + // 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; + } + } + } + } + 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 { + 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: false, + peer_engaged: true, + requested_by_peer: !asked, + carried: false, + }); + 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, + now: Instant, + ) -> bool { + match self.link.as_mut() { + Some(link) if link.id == link_id => { + link.platform_engaged = false; + self.end(reason, true, now); + true + } + _ => { + // 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 + } + } + } + + /// The application ends the link with `peer`. + pub(crate) fn close(&mut self, peer: &str, now: Instant) -> bool { + if self.peer() != Some(peer) { + return false; + } + self.end(CloseReason::Closed, true, now); + 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 { + 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 { + return; + }; + 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. + // 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; + } + if 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, now: Instant) { + if self + .link + .as_ref() + .is_some_and(|link| link.peer == peer && link.state == FastLinkState::Up) + { + self.end(CloseReason::Lost, true, now); + } + } + + /// 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; + link.carried = true; + } + } + } + + /// 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; + link.carried = true; + 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, now); + } + } + + /// 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 + /// 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; + } + // 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; + } + // 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, now)); + 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)); + } + } + + /// Counts an offer `peer` made without being asked that ended: one that + /// 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). + /// [`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; + } + // 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 + | CloseReason::Superseded + ) + { + return; + } + // 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, now)); + 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(); + } + 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(); + } + self.ended.push_back((link_id.to_string(), 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, 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; + }; + // 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); + self.remember_ended(&link.id, now); + // 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, by_peer, reason, now); + } + 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())); + // 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); + } + if link.requested_by_peer { + self.count_offer(&link.peer, link.carried, by_peer, reason, now); + } + } + 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`. 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 = 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 + .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() + } + + /// 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)] +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, + accept_unrequested: true, + } + } + + fn join_roles() -> FastLinkRoles { + FastLinkRoles { + can_host: false, + can_join: true, + accept_unrequested: 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}"); + + // 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] + 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, + re: None, + }; + 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() + }, + // 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() + }, + 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()); + // 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()); + 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, t0); + 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, + re: None, + }; + 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, t0)); + 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, 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(), "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"); + + 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); + // 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 + ); + 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)); + + // 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] + 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_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(); + 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_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, + re: None, + }; + 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_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, + re: None, + }; + 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_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, + re: None, + }; + iphone.on_frame( + LOW, + HIGH, + Frame::new(&id, FrameBody::Offer(offer)), + fresh(3), + t0, + 0, + ); + 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, + re: None, + }; + 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_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, + re: None, + }; + 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 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_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(); + 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, + re: None, + }; + 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_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, + re: None, + }; + 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_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 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_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_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_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_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; 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() {} + 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, so its transfers are released and, carrying + // nothing, it is counted. + let mut android = machine(host_roles()); + let mut iphone = machine(join_roles()); + 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] + 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()); + 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 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 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_miss_long_ago_is_not_one_in_a_row() { + let mut android = machine(host_roles()); + let t0 = Instant::now(); + let 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(); + // 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, + re: None, + }; + 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(); + // 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, + re: None, + }; + 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(); + 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/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/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/blocking.rs b/crates/offline-protocol/src/protocol/blocking.rs index d51574f95..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) { @@ -150,6 +154,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 +1511,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/fast_link.rs b/crates/offline-protocol/src/protocol/fast_link.rs new file mode 100644 index 000000000..a29718901 --- /dev/null +++ b/crates/offline-protocol/src/protocol/fast_link.rs @@ -0,0 +1,361 @@ +//! 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, FrameBody, FreshLink, +}; +use crate::{Error, Event, Result}; + +impl OfflineProtocol { + /// 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, + 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. + /// + /// 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 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. + 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, Instant::now()); + self.flush_fast_link(); + closed + } + + /// 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, reason, 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) { + 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 { + 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), Instant::now()); + 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, Instant::now()); + self.flush_fast_link(); + } + + /// 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 + /// 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; + }; + // 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. + 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, + 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 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 + } + + /// 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 + .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)); + } + 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(); + } + } + + /// 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<()> { + // 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; + 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 2932cc5cd..3c698d849 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() { @@ -1623,9 +1635,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) { @@ -1656,6 +1678,16 @@ 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 { + 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 } DecryptResult::Empty => { diff --git a/crates/offline-protocol/src/protocol/mod.rs b/crates/offline-protocol/src/protocol/mod.rs index a3eb03b3c..b72841575 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; @@ -438,6 +439,32 @@ 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, + + /// 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, + + /// 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 @@ -1319,6 +1346,9 @@ 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(), + 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(), @@ -1537,6 +1567,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 +1741,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; @@ -2380,6 +2412,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 @@ -2413,6 +2450,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_for(crate::fast_link::CloseReason::Background); Ok(()) } @@ -3735,6 +3777,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) { @@ -3865,6 +3916,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/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/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/send.rs b/crates/offline-protocol/src/protocol/send.rs index 539693c89..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, DEFAULT_MEDIA_WINDOW_SIZE}; - (DEFAULT_CHUNK_SIZE, DEFAULT_MEDIA_WINDOW_SIZE) + 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. @@ -4265,6 +4265,17 @@ 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) { + 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 // `defer_for_ack_capacity` first, so this is only reachable through a @@ -7042,6 +7053,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 473e0d6de..c5451f468 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/fast_link.rs b/crates/offline-protocol/src/protocol/tests/fast_link.rs new file mode 100644 index 000000000..79f1fc65e --- /dev/null +++ b/crates/offline-protocol/src/protocol/tests/fast_link.rs @@ -0,0 +1,690 @@ +//! 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, true); + bob.protocol.set_fast_link_roles(false, true, 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, 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, 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, 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())) + ); +} + +/// 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_keeps_512_kib_in_flight() { + use offline_protocol_core::ContentType; + use offline_protocol_transport::PeerLink; + + use crate::constants::{CHUNK_SIZE_PEER_STREAM, 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; CHUNK_SIZE_PEER_STREAM * 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 * CHUNK_SIZE_PEER_STREAM, + 512 * 1024 + ); +} + +/// 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()); +} + +/// 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()))) + ); +} + +/// Two phones that meet over a shared LAN while a link they both hold is +/// 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; + + 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] +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())) + ); +} + +/// 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)); +} + +/// 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]); +} + +/// 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] +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] +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/crates/offline-protocol/src/protocol/tests/mod.rs b/crates/offline-protocol/src/protocol/tests/mod.rs index 17f9b16e4..291247d42 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; @@ -1888,6 +1889,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 +1973,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 +2173,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 +2296,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 +2442,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 +2781,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 +3148,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 +3234,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 +3279,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 +3423,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 +4035,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 +16058,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!( "{}{}", @@ -21156,6 +21232,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!( "{}{}", @@ -21370,6 +21447,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!( "{}{}", @@ -21458,6 +21536,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!( "{}{}", @@ -21549,6 +21628,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!( "{}{}", @@ -21603,6 +21683,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!( "{}{}", @@ -23160,6 +23241,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!( "{}{}", @@ -23722,6 +23804,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 @@ -41448,6 +41565,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!( "{}{}", @@ -43308,6 +43426,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/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/README.md b/docs/README.md index 67b752413..a91610264 100644 --- a/docs/README.md +++ b/docs/README.md @@ -92,7 +92,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 | @@ -100,12 +100,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..75bd35607 --- /dev/null +++ b/docs/adr/0038-a-fast-link-is-offered-inside-the-session.md @@ -0,0 +1,178 @@ +# 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 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: + +- 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. 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: + 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. 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 + 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 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. + +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 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 + +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 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 + 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. 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. +- 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/bridges/README.md b/docs/bridges/README.md index 6096f64b1..e20f858bc 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,18 @@ 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 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 layer, so a layer that omits it compiles and drops it: the TypeScript params diff --git a/docs/mobile-permissions.md b/docs/mobile-permissions.md index 9af81359f..a08fe04ce 100644 --- a/docs/mobile-permissions.md +++ b/docs/mobile-permissions.md @@ -128,6 +128,33 @@ 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 +(`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. 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 +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. + +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 diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 37c1d3cc1..31e8eef90 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -1448,6 +1448,85 @@ 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 +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 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 +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, 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 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 +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. + +**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. 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 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. 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 +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/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/docs/spec/control-messages.md b/docs/spec/control-messages.md index 37cbfbb04..5a5763f84 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,54 @@ 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`, 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: + +- **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 (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. +- **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 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 + of its clock or more than `ttl_ms` plus 300 s behind it, and answers it with + 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`, +`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 Control frames are authenticated with an Ed25519 signature over a canonical 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. diff --git a/docs/spec/local-api.md b/docs/spec/local-api.md index d06c734c2..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 | @@ -655,6 +668,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` | diff --git a/docs/spec/stream-framing.md b/docs/spec/stream-framing.md index 4532e5b35..9b77195ab 100644 --- a/docs/spec/stream-framing.md +++ b/docs/spec/stream-framing.md @@ -311,6 +311,15 @@ 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 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 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..8df682292 --- /dev/null +++ b/docs/state-machines/fast-link.md @@ -0,0 +1,266 @@ +# 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 (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 + 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, 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 +`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 + +| 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, 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 + +| 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` (`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 + +**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) 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 +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. 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. + +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 +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 +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, 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 +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 +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. 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. + +**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 +this rule its offer prompted the requester's user to join a network that had +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 +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 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. + +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 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 +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. 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 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 +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, 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 + +`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. 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 + +- **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. +- **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; + 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, 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 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 + 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. 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, 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 "