Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / share / PROTOCOL_CONTRACT.md

PROTOCOL_CONTRACT.md21.8 KiBRenderedCodeRaw
1# Share — JNI Protocol Contract (Kotlin ↔ Rust)
2
3This is the **single source of truth** for the session API between the Kotlin app layer
4(Compose UI, NSD/BLE discovery, TCP transport — **appdev**) and the Rust protocol crate
5(UKEY2, protobuf framing, secure messages, payload — **rustdev**).
6
7> Do not change native method names, signatures, or the crate/library names
8> without updating this doc, `ShareNative.kt`, *and* `share/src/main/rust/src/lib.rs`
9> together. Renames break JNI linkage at runtime.
10
11## 1. Crate & library
12
13- **Cargo crate:** `share_nearby` at `share/src/main/rust/` (members entry in root `Cargo.toml`).
14- **Shared lib:** `libshare_nearby.so` built via `rustNativeLib("share_nearby", "share")` in
15 `share/build.gradle.kts` and wired into `android { ... jniLibs sourceDirectory }` (copy
16 `maps` / `library:e2ee-p2p`). Crate exposes `crate-type = ["cdylib","rlib"]`.
17- **Kotlin JNI class:** `com.vayunmathur.share.protocol.ShareNative` (the `System.loadLibrary`
18 is `share_nearby`).
19
20## 2. Ownership & threading
21
22- **Kotlin owns:** BLE + mDNS advertisement/scanning (Nearby Connections
23 `BleAdvertisement` service-data under GATT `0xFEF3`, and `_FC9F5ED42C8A._tcp`), TCP
24 listen/connect, file I/O, the foreground notification, permissions.
25- **Rust owns:** the Nearby Connections connection handshake
26 (`CONNECTION_REQUEST`/`CONNECTION_RESPONSE`), the BetoCore UKEY2 D2D handshake
27 (`ukey2_connections` + `crypto_provider_default` rustcrypto,
28 **`NextProtocol::Aes256CbcHmacSha256`**), the `D2DConnectionContextV1` secure channel,
29 the mandatory paired-key exchange, `OfflineFrame` / Sharing `Frame` encode+decode,
30 payload chunking, keep-alive, the per-session outbound queue, and the byte codecs for the
31 `BleAdvertisement`, the Nearby Sharing endpoint info and the `WifiLanServiceInfo` mDNS
32 instance name.
33- **Transport rule:** Kotlin never hands Rust a socket and Rust never performs I/O. All
34 bytes cross as `byte[]` via `feedInbound` / `drainOutbound`. Advertisement bytes cross as
35 `byte[]` too; Rust returns raw bytes and Kotlin applies Base64 where the medium needs it,
36 because Base64 is a platform API.
37- **Threading:** calls for a given session handle must be serialized by the caller (one
38 coroutine / thread per session). Rust guards the session map with a `Mutex`, but callers
39 should still avoid concurrent `feedInbound` + `drainOutbound` on the same handle. The
40 discovery helpers take no handle and are pure functions.
41
42### Layering
43
44```
45TCP ►─ int32be(len) ‖ body
46 │
47 ├─ OfflineFrame (CONNECTION_REQUEST, plaintext)
48 ├─ Ukey2Message (all three, plaintext)
49 ├─ OfflineFrame (CONNECTION_RESPONSE, plaintext)
50 └─ D2D-encrypted body
51 └─ OfflineFrame
52 └─ V1Frame
53 └─ PayloadTransferFrame
54 ├─ BYTES payload = Sharing Frame
55 │ (INTRODUCTION / RESPONSE / PAIRED_KEY_*)
56 └─ FILE payload = file bytes
57```
58
59A Sharing `Frame` is **never** framed directly on the socket: it is always the body of a
60BYTES payload. See `share/QUICK_SHARE_VERIFICATION.md` for the citations.
61
62### Handshake phases
63
64The order is `CONNECTION_REQUEST → UKEY2 → CONNECTION_RESPONSE`, and the response is
65exchanged **in plaintext by both sides**. Encryption begins only once both responses
66have been seen.
67
68| Phase | Wire body | Who sends | Citation |
69|---|---|---|---|
70| `Connecting` | plaintext `OfflineFrame` `CONNECTION_REQUEST` | initiator | `p000\dnsi.java:9582` |
71| `Ukey2` | plaintext `Ukey2Message` × 3 | client, server, client | `p000\dnij.java:92-107`, `:176-180` |
72| `ConnectionAccept` | plaintext `OfflineFrame` `CONNECTION_RESPONSE` | **both**, independently | `p000\dncj.java:1204` (written before `mo63639c()` at `:1208`) |
73| `PairedKey` | encrypted `PAIRED_KEY_ENCRYPTION` + `PAIRED_KEY_RESULT` | both | see §6 |
74| `Ready` | encrypted `INTRODUCTION` / `RESPONSE` / payloads | both | — |
75
76The initiator writes the request and its UKEY2 ClientInit **back to back** without
77waiting: GMS does the same (`p000\dnsi.java:9582` then `:9633` = `startClient`), and a
78responder that answers the request before UKEY2 makes a real peer try to parse the
79response as a `Ukey2Message`. Encryption is installed exactly where
80`evaluateConnectionResult` installs it — after both sides accept
81(`p000\dnsi.java:4319`, gate at `:4327-4339`).
82
83Accepting at this layer is **programmatic**, not a user prompt: Quick Share calls
84`acceptConnection` as soon as the connection is offered (`p000\dzuj.java:76`). The
85user-facing accept is the Sharing-layer `INTRODUCTION` / `RESPONSE`, i.e. `nativeAccept`.
86
87## 3. Session lifecycle (call order)
88
89```
90// isInitiator: true for the side that dialled the TCP socket, false for the acceptor.
91// The initiator sends CONNECTION_REQUEST, is the UKEY2 client, and therefore speaks
92// first in the response exchange too, so getting this wrong deadlocks the handshake.
93handle = nativeInit(localName, localEndpointInfo, localEndpointId, isInitiator)
94loop {
95 bytes = tcpSocket.read() // blocking read
96 if (bytes != null) nativeFeedInbound(handle, bytes)
97 while ((rec = nativeDrainReceived(handle)) != null) appendToFile(rec) // §6 layout
98 while ((out = nativeDrainOutbound(handle)) != null) tcpSocket.write(out)
99 // drive UI from nativeQueryState / nativeQueryPendingFiles
100}
101
102// Sending:
103nativeSetFilesToSend(handle, filesJson) // stage metadata
104nativeQueueIntroduction(handle) // held until the paired-key phase ends
105// once state == TRANSFERRING, per file:
106nativeOpenFile(handle, name, size); nativeWriteChunk(handle, chunk)*; nativeCloseFile(handle)
107
108// Receiving:
109nativeAccept(handle, userAccepted, destDir) // when state == AWAITING_ACCEPT
110// destDir is vestigial: Rust never touches the filesystem, and Kotlin stages received
111// bytes itself from nativeDrainReceived.
112
113// Diagnosing:
114reason = nativeQueryFailureReason(handle) // null while healthy
115
116nativeSendKeepAlive(handle) // optional, for long idle transfers
117nativeDestroy(handle) // always (finally / onCleared)
118
119// Discovery: one endpoint id and one endpoint info for the whole device, shared by all
120// three of the BLE advertisement, the mDNS record and CONNECTION_REQUEST.
121type = nativeMdnsServiceType() // "_FC9F5ED42C8A._tcp"
122ei = nativeBuildEndpointInfo(deviceName, DEVICE_TYPE_PHONE)
123sd = nativeBuildBleAdvertisement(ei, deviceToken, fast = false)
124advertise(sd) // addServiceData(0000FEF3-..., sd)
125wlsi = nativeBuildWifiLanServiceInfo(endpointId) // 8 bytes -> Base64 instance name
126registerService(base64(wlsi), txt = { "n": base64(ei), "IPv4": addr }, port)
127info = nativeParseBleAdvertisement(scannedServiceData) // null = not ours
128peer = nativeParseEndpointInfo(info) // null = a real device would drop it
129```
130
131`nativeDrainReceived` must be called after **every** `nativeFeedInbound`: Rust drops each
132chunk as it hands it over, so an undrained chunk is a lost chunk.
133
134Errors are returned as negative `int` codes from the `native* -> int` methods; a null
135`byte[]`/`String` from `drainOutbound` / `queryPendingFiles` / the discovery helpers means
136"nothing, no session, or not parseable".
137
138## 4. State machine
139
140`nativeQueryState` returns the `State` ordinal below. Kotlin maps it via `ShareState`.
141
142| Code | Name | Meaning |
143|------|------------------|---------|
144| 0 | `Handshaking` | `CONNECTION_REQUEST`/`RESPONSE`, UKEY2, and the paired-key exchange are in progress; keep pumping bytes. |
145| 1 | `AwaitingAccept` | An `INTRODUCTION` decoded; the UI should surface `queryPendingFiles` and prompt Accept/Reject. |
146| 2 | `Transferring` | Accepted; payload bytes are flowing (`openFile`/`writeChunk`/`closeFile`). |
147| 3 | `Completed` | Receiving: every announced payload arrived. Sending: every payload the `INTRODUCTION` announced has had its `FLAG_LAST` chunk written. |
148| 4 | `Failed` | Protocol failure, peer rejection, or local rejection. |
149
150## 5. JNI surface (exact signatures)
151
152Class: `com.vayunmathur.share.protocol.ShareNative`
153Rust symbols: `Java_com_vayunmathur_share_protocol_ShareNative_<method>` (`extern "system"`).
154
155```kotlin
156internal object ShareNative {
157 external fun nativeInit(localName: String, localEndpointInfo: ByteArray, localEndpointId: String, isInitiator: Boolean): Long
158 external fun nativeFeedInbound(handle: Long, bytes: ByteArray): Int
159 external fun nativeDrainOutbound(handle: Long): ByteArray? // null = nothing to send
160 external fun nativeQueryState(handle: Long): Int // State code, -1 = bad handle
161 external fun nativeQueryPendingFiles(handle: Long): ByteArray? // JSON utf8, see §6
162 external fun nativeAccept(handle: Long, accept: Boolean, destDir: String): Int
163 external fun nativeSetFilesToSend(handle: Long, json: ByteArray): Int // same JSON shape as §6
164 external fun nativeQueueIntroduction(handle: Long): Int
165 external fun nativeSendKeepAlive(handle: Long): Int
166 external fun nativeOpenFile(handle: Long, fileName: String, fileSize: Long): Int
167 external fun nativeWriteChunk(handle: Long, chunk: ByteArray): Int
168 external fun nativeCloseFile(handle: Long): Int
169 external fun nativeDrainReceived(handle: Long): ByteArray? // one §6 record, null = none
170 external fun nativeQueryFailureReason(handle: Long): String? // null = healthy
171 external fun nativeQueryPeerName(handle: Long): String? // null until CONNECTION_REQUEST is read
172 external fun nativeQueryTrace(handle: Long): String? // recent protocol events, one per line
173 external fun nativeDestroy(handle: Long) // void
174
175 // Discovery — derived in ble_adv.rs from SHA-256("NearbySharing"). Pure functions.
176 external fun nativeMdnsServiceType(): String? // "_FC9F5ED42C8A._tcp"
177 external fun nativeBleServiceIdHash(): ByteArray? // FC 9F 5E
178 external fun nativeBuildBleAdvertisement(data: ByteArray, deviceToken: ByteArray, fast: Boolean): ByteArray?
179 external fun nativeParseBleAdvertisement(serviceData: ByteArray): ByteArray? // null = not ours
180 external fun nativeFastInitiationServiceData(metadata: ByteArray): ByteArray? // FC128E ‖ metadata
181
182 // Endpoint info + WifiLanServiceInfo — endpoint_info.rs. Raw bytes; Kotlin does Base64.
183 external fun nativeBuildEndpointInfo(deviceName: String, deviceType: Int): ByteArray?
184 external fun nativeParseEndpointInfo(blob: ByteArray): ByteArray? // JSON utf8, null = invalid
185 external fun nativeBuildWifiLanServiceInfo(endpointId: String): ByteArray? // 8 bytes
186 external fun nativeParseWifiLanServiceInfo(raw: ByteArray): ByteArray? // JSON utf8
187
188 // Nearby Presence — retained but NOT on the Quick Share path. See §7.
189 external fun nativeBuildPresenceAdvert(deviceName: String): ByteArray?
190 external fun nativeParsePresenceAdvert(serviceData: ByteArray): ByteArray?
191 external fun nativeParsePresenceAdvertName(advertBytes: ByteArray): String?
192}
193```
194
195Kotlin also ships `ShareSession` (`share/domain/protocol/ShareSession.kt`) as the
196`AutoCloseable` wrapper (handle lifetime, JSON decode, `ShareState` mapping) — the
197preferred call site for app code. Direct `ShareNative` calls are allowed but
198`ShareSession` should be used for lifecycle correctness. The discovery helpers are called
199directly on `ShareNative` (no session handle); callers must tolerate `null`.
200
201## 6. Data formats
202
203- **Bytes:** all wire frames are opaque `byte[]`. Kotlin does no framing. Rust applies a
204 **4-byte big-endian int32 length prefix** to every message on the socket — the UKEY2
205 handshake messages and, once the channel is encrypted, every `OfflineFrame` — and it
206 buffers partial reads internally. Peer-supplied lengths are bounded before allocation.
207- **Secure channel:** the UKEY2 record protocol is **`AES_256_CBC-HMAC_SHA256`** with a
208 per-direction sequence number, via
209 `D2DConnectionContextV1::encode_message_to_peer` / `decode_message_from_peer`
210 (`associated_data` `None`). GMS rejects any other record protocol outright, so this is
211 not a tunable.
212- **Frame nesting:** see the diagram in §2. A Sharing `Frame` is always the body of a BYTES
213 payload inside `PAYLOAD_TRANSFER`; file bytes are FILE payloads split into 16 KiB
214 `PayloadChunk`s with `FLAG_LAST` on the final one. The header is repeated on every chunk.
215- **Paired key:** after the `CONNECTION_RESPONSE` exchange both sides must exchange
216 `PAIRED_KEY_ENCRYPTION` and `PAIRED_KEY_RESULT` before the introduction. `:share` holds
217 no contact certificate, so it sends a 72-byte random `signed_data` and a 6-byte random
218 `secret_id_hash` — the exact widths GMS uses when signing fails — and answers
219 `PAIRED_KEY_RESULT{UNABLE}`. Skipping this makes the peer time out after roughly five
220 seconds.
221- **`CONNECTION_RESPONSE`:** `status` (field 1) is `0` to accept and `8004` to reject
222 (`p000\dncj.java:1204`, `:1622`), and `response` (field 3) is `1 = ACCEPT`,
223 `2 = REJECT` (`p000\dnlx.java:1041-1051`). Both are written. `status = 0` is emitted
224 **explicitly**: with field 3 absent, `p000\dnsi.java:6911` reads a merely-defaulted
225 status as a rejection.
226- **Endpoint info** (`nativeBuildEndpointInfo` / `nativeParseEndpointInfo`). The Nearby
227 Sharing blob a peer needs to list us, minimum 17 bytes:
228 `header(1) ‖ salt(2) ‖ encryptedMetadataKey(14) ‖ nameLen(1) ‖ name(1..32) ‖ TLVs*`, where
229 the header is `version` in bits 7..5 (we write 1), the contact-only flag in bit 4 (we
230 write 0 so the plaintext name follows) and `deviceType` in bits 3..1. Names longer than 32
231 bytes are truncated on a UTF-8 boundary, since the peer rejects a name that decodes to
232 U+FFFD. The metadata key is 16 random bytes: Everyone mode never needs it to decrypt to
233 anything. Cited in full in `share/QUICK_SHARE_VERIFICATION.md`.
234- **`WifiLanServiceInfo`** (`nativeBuildWifiLanServiceInfo` / `nativeParseWifiLanServiceInfo`).
235 The mDNS instance name, exactly 8 bytes:
236 `(version << 5) | pcp` with `version = 1` and `pcp = 3`, then the 4 ASCII endpoint-id
237 bytes, then the 3-byte service-id hash `FC 9F 5E`. The trailing UWB-address and flags
238 bytes are optional and deliberately omitted. Rust returns raw bytes; Kotlin Base64s them
239 with `URL_SAFE or NO_PADDING or NO_WRAP`, which is the flag GMS passes.
240- **One identity per device.** The same endpoint id and the same endpoint-info blob must go
241 into the BLE advertisement, the mDNS record (instance name and `n` TXT) **and**
242 `nativeInit`'s `localEndpointId` / `localEndpointInfo`, because the peer matches
243 `CONNECTION_REQUEST` against what it discovered and hangs up otherwise. Renaming the
244 device changes the blob, so it must be rebuilt and re-advertised.
245- **`queryPendingFiles` / `setFilesToSend`:** UTF-8 JSON `byte[]` —
246 `[{"name":"photo.jpg","sizeBytes":1234,"mimeType":"image/jpeg"}]`. An empty list is `[]`.
247 `sizeBytes` must be a plain non-negative integer.
248- **`drainReceived` record.** One decrypted FILE `PayloadChunk`, self-describing, all
249 integers big-endian:
250
251 ```
252 u8 version = 1
253 i64 payload_id
254 i64 offset (within the payload)
255 i64 total_size (the payload's announced length)
256 u8 flags (bit 0 = last chunk of this payload)
257 u16 name_len
258 u8[] name (UTF-8)
259 u32 body_len
260 u8[] body
261 ```
262
263 BYTES payloads are Sharing frames, handled inside Rust, and never appear here. Rust
264 keeps no copy of the body, so memory is constant in the file size — and an undrained
265 chunk is lost.
266- **Where received files go.** Kotlin appends each record to
267 `filesDir/received/<name>` (`ReceivedFileStore`) and closes the file on the last-chunk
268 flag. Nothing is written to public storage: `:share` declares no storage permission.
269 The only exits are **Share** (system chooser over a `FileProvider` URI) and **Save**
270 (copy into a directory the user picks with `OpenDocumentTree`, via `DocumentsContract`).
271- **`BleAdvertisement` service-data:** header byte
272 `(version<<5) | (socketVersion<<2) | (fast?2:0) | (rx?1:0)` with version and socket
273 version both 2, then — in extended mode — the 3-byte `serviceIdHash` `FC 9F 5E`, a 4-byte
274 big-endian data length, the data, and an optional 2-byte device token. Fast mode omits the
275 hash and uses a single length byte, within a 27-byte total budget. Built and parsed in
276 `share/src/main/rust/src/ble_adv.rs`; advertised under
277 `0000FEF3-0000-1000-8000-00805F9B34FB`. The `data` payload is the endpoint-info blob
278 below, and a peer that cannot parse it discards the whole advertisement.
279- **`parsePresenceAdvert`:** UTF-8 JSON `byte[]` —
280 `{"deviceName":"Pixel 7","deviceType":1,"txPower":0,"isTruncated":false}` (`deviceType`
281 per `np_adv::shared_data::DeviceType`). Retained but unused by discovery; see §7.
282- **Files:** Kotlin owns both ends of the filesystem — it reads outgoing files and stages
283 incoming ones — while Rust owns chunk sequencing, offsets and payload-id bookkeeping.
284 Received payloads are keyed by the `payload_id` announced in the `INTRODUCTION`.
285- **Errors:** `nativeFeedInbound` / `nativeAccept` / `native*File` return `0` on success and
286 `<0` on error (`-1` bad handle or args, `-2` wrong state or protocol failure). The caller
287 should transition to `Failed` and surface `nativeQueryFailureReason`, which names the
288 phase that broke.
289
290## 7. Implementation map
291
292Inside `share/src/main/rust/src/`:
293
294- `frame.rs` — 4-byte big-endian framing with a sanity bound, plus the `prost` definitions
295 for the Sharing wire format (`Frame` → `V1Frame` → oneof, `FileMetadata`,
296 `TextMetadata`, `WifiCredentialsMetadata`, `AppMetadata`, `ConnectionResponseFrame`,
297 `PairedKey*`) and the Nearby Connections wire format (`OfflineFrame` → `V1Frame` →
298 `ConnectionRequest` / `ConnectionResponse` / `PayloadTransfer` / `KeepAlive` /
299 `Disconnection`). **Every field carries a `p000\*.java` citation** naming the decompiled
300 class it was recovered from.
301- `payload.rs` — frame builders (introduction with `payload_id`/`use_case`/`start_transfer`,
302 accept/reject, paired-key decoys, connection request/response, keep-alive), the BYTES vs
303 FILE payload split, and chunking.
304- `session.rs` — the five-phase state machine (`Connecting` → `Ukey2` →
305 `ConnectionAccept` → `PairedKey` → `Ready`) over `ukey2_connections` with
306 `HandshakeImplementation::Spec`, `NextProtocol::Aes256CbcHmacSha256` and
307 `crypto_provider_default::CryptoProviderImpl`, plus the received-chunk queue.
308- `ble_adv.rs` — the `BleAdvertisement` byte codec (extended and fast mode, with their
309 length budgets) and the `SHA-256("NearbySharing")` derivations for the mDNS service type
310 and the BLE `serviceIdHash`.
311- `endpoint_info.rs` — the Nearby Sharing endpoint-info blob and the `WifiLanServiceInfo`
312 mDNS instance name, both build and parse, with golden-byte tests. These are what make a
313 device *listed*; see §6 and `share/QUICK_SHARE_VERIFICATION.md`.
314- `presence.rs` — `np_adv` V0 unencrypted build/parse. **Retained but not on the Quick Share
315 path**: Presence is a separate subsystem advertising under `0xFCF1`, BetoCore's
316 credential/D2D/payload FFI has no Java callers in GMS 26.24.34, and whether betocore is
317 live for Quick Share at all could not be determined. Discovery uses `ble_adv.rs`.
318
319Ground truth and the list of corrected defects live in
320`share/QUICK_SHARE_VERIFICATION.md`. There is no `nearby_clone` checkout and no `.proto`
321file anywhere in this claim chain — the tags come from the decompiled protobuf-lite schema.
322
323## 8. What appdev must implement
324
325- `MainActivity` + Compose screens (using `:library:ui` — direct
326 `androidx.compose.material*` imports are banned by lint) for:
327 discovery/teaming (BLE + mDNS), nearby list, incoming banner (Accept/Reject),
328 progress, and completion. Wire `ShareSession` in a `ViewModel` (one session per peer).
329- TCP transport: listen on an ephemeral port, advertise via BLE/mDNS, connect to a peer,
330 pump `feedInbound`/`drainOutbound` on a background dispatcher, post state to the UI via
331 `queryState` polling. The dialling side must construct its session with
332 `isInitiator = true` and the accepting side with `false`.
333- BLE/mDNS discovery: build one endpoint-info blob with `nativeBuildEndpointInfo(...)` and
334 use it everywhere. Register under `nativeMdnsServiceType()` with the Base64
335 `nativeBuildWifiLanServiceInfo(endpointId)` as the instance name, the Base64 blob in the
336 `n` TXT attribute and the local address in `IPv4`; advertise
337 `nativeBuildBleAdvertisement(blob, token, fast)` under `0xFEF3`, preferring extended
338 advertising because a full-length blob does not fit a legacy advertisement; scan with
339 `setLegacy(false)` and filter with `nativeParseBleAdvertisement` then
340 `nativeParseEndpointInfo` (null from either means "not a Quick Share advertiser, or one a
341 real device would drop"). Optionally beacon `0xFE2C` FastInitiation. Only the mDNS leg
342 yields a connectable host/port.
343- File I/O: `ReceivedFileStore` stages incoming payloads in app-private storage from
344 `nativeDrainReceived`; the UI offers Share and Save per file. On the send side,
345 `openFile`/`writeChunk`/`closeFile` during `Transferring`.
346- Foreground service `ShareTransferService` for transfers that outlive the Activity.
347- Permissions flow: `NEARBY_WIFI_DEVICES` / `BLUETOOTH_*` / `ACCESS_FINE_LOCATION`
348 (see `AndroidManifest.xml`), and the `ACTION_SEND` / `ACTION_SEND_MULTIPLE`
349 incoming share intents.
350
351## 9. Build & verify
352
353```powershell
354# Build just the Share module (no other apps):
355./gradlew :share:assembleDev
356
357# Lint (Material-via-:library:ui, manifests, etc.):
358./gradlew :share:lintDev
359
360# Rust only (host build, no NDK):
361cargo test -p share_nearby
362cargo check -p share_nearby
363# NDK:
364cargo check -p share_nearby --target aarch64-linux-android
365```