Modern Apps git

← Modern-Apps.git

share: make Quick Share discovery interop work against real GMS (BLE envelope, Local Network Protections, UKEY2 protobuf key)

Commit
2448cdf2b79273f8bff63c4f49beac75c7742cb3
Author
vayun-mathur <[email protected]>
When
2026-08-18 22:29 UTC (3 months ago)
Parents
2e308a2
A Pixel now lists this device in its Quick Share sheet and reaches an
encrypted, ready session. Every item below was verified on hardware
against a Pixel 7 Pro running Quick Share on GMS 26.24.34.

- add ACCESS_LOCAL_NETWORK; Android 16+ Local Network Protections made
  NsdManager.registerService throw SecurityException, so mDNS never
  registered
- nest the Nearby Sharing endpoint-info blob inside the Nearby
  Connections BLE envelope (pcp/version | serviceIdHash | endpointId |
  len | blob), recovered by capturing a real Quick Share advertisement;
  a Pixel now lists the device
- new endpoint_info.rs: endpoint-info and WifiLanServiceInfo codecs with
  golden-byte tests, including a real captured Pixel advertisement as a
  test vector
- mDNS record now carries the Base64 WifiLanServiceInfo instance name and
  Base64 endpoint info in the `n` TXT attribute
- BLE: extended advertising with a fast-mode legacy fallback,
  service-data-only advertisement, non-legacy scan settings
- UKEY2: switch to HandshakeImplementation::PublicKeyInProtobuf — GMS
  parses the peer public key as a protobuf (jgzt.m136727g), so SEC1
  encoding drew a BAD_MESSAGE_DATA alert
- paired-key exchange is now reactive (responder speaks first); sending
  it proactively drew a DISCONNECTION 250ms later
- stop gating readiness on the peer's PAIRED_KEY_RESULT, which GMS never
  sends
- BYTES payloads: send a data chunk plus an empty FLAG_LAST terminator,
  and reassemble inbound ones by offset (matches GMS's observed
  chunking)
- answer KEEP_ALIVE and decline BANDWIDTH_UPGRADE with UPGRADE_FAILURE
  (event 5, per ivjo.java)
- one endpoint id and one endpoint info shared by BLE, mDNS and
  CONNECTION_REQUEST
- add a session frame trace (nativeQueryTrace) for diagnosing peers that
  stop responding
- received payloads are streamed to app-private staging via
  ReceivedFileStore and surfaced with Share/Save through a FileProvider,
  replacing the unused FileSaveHelper

This is work in progress: transfers to and from a real device still
fail. GMS declares the endpoint lost roughly 10s into a live connection
and never sends its INTRODUCTION, so no payload ever changes hands.
TcpTransport also retains temporary IN/OUT hex logging used for that
investigation.

Diff

share/PROTOCOL_CONTRACT.md
diff --git a/share/PROTOCOL_CONTRACT.md b/share/PROTOCOL_CONTRACT.mdindex b3071d3d44..e2bb209eb6 100644--- a/share/PROTOCOL_CONTRACT.md+++ b/share/PROTOCOL_CONTRACT.md@@ -19,40 +19,121 @@ This is the **single source of truth** for the session API between the Kotlin ap  ## 2. Ownership & threading -- **Kotlin owns:** BLE + NSD advertisement/scanning (GATT 0xFCF1 service-data via `presence.rs`), TCP listen/connect, file I/O (SAF/MediaStore),-  foreground notification, permissions.-- **Rust owns:** BetoCore UKEY2 D2D handshake (`ukey2_connections` + `crypto_provider_default` rustcrypto, `NextProtocol::Aes256GcmSiv`), `D2DConnectionContextV1` AES-256-GCM-SIV per-direction seq, frame encode/decode, `Introduction` + payload chunking (16 KiB, `FLAG_LAST`), per-session outbound queue, and Nearby Presence advert build/parse (`np_adv` UnencryptedEncoder, Everyone/public only).-- **Transport rule:** Kotlin never hands Rust a socket and Rust never performs I/O. All bytes-  cross as `byte[]` via `feedInbound` / `drainOutbound`. Presence adverts cross as service-data `byte[]` via `nativeBuildPresenceAdvert` / `nativeParsePresenceAdvert`.-- **Threading:** Calls for a given session handle must be serialized by the caller (one+- **Kotlin owns:** BLE + mDNS advertisement/scanning (Nearby Connections+  `BleAdvertisement` service-data under GATT `0xFEF3`, and `_FC9F5ED42C8A._tcp`), TCP+  listen/connect, file I/O, the foreground notification, permissions.+- **Rust owns:** the Nearby Connections connection handshake+  (`CONNECTION_REQUEST`/`CONNECTION_RESPONSE`), the BetoCore UKEY2 D2D handshake+  (`ukey2_connections` + `crypto_provider_default` rustcrypto,+  **`NextProtocol::Aes256CbcHmacSha256`**), the `D2DConnectionContextV1` secure channel,+  the mandatory paired-key exchange, `OfflineFrame` / Sharing `Frame` encode+decode,+  payload chunking, keep-alive, the per-session outbound queue, and the byte codecs for the+  `BleAdvertisement`, the Nearby Sharing endpoint info and the `WifiLanServiceInfo` mDNS+  instance name.+- **Transport rule:** Kotlin never hands Rust a socket and Rust never performs I/O. All+  bytes cross as `byte[]` via `feedInbound` / `drainOutbound`. Advertisement bytes cross as+  `byte[]` too; Rust returns raw bytes and Kotlin applies Base64 where the medium needs it,+  because Base64 is a platform API.+- **Threading:** calls for a given session handle must be serialized by the caller (one   coroutine / thread per session). Rust guards the session map with a `Mutex`, but callers-  should still avoid concurrent `feedInbound` + `drainOutbound` on the same handle. Presence `nativeBuild`/`nativeParse` are pure functions, no handle, thread-safe.+  should still avoid concurrent `feedInbound` + `drainOutbound` on the same handle. The+  discovery helpers take no handle and are pure functions.++### Layering++```+TCP  ►─  int32be(len) ‖ body+                        │+                        ├─ OfflineFrame             (CONNECTION_REQUEST, plaintext)+                        ├─ Ukey2Message             (all three, plaintext)+                        ├─ OfflineFrame             (CONNECTION_RESPONSE, plaintext)+                        └─ D2D-encrypted body+                             └─ OfflineFrame+                                  └─ V1Frame+                                       └─ PayloadTransferFrame+                                            ├─ BYTES payload = Sharing Frame+                                            │    (INTRODUCTION / RESPONSE / PAIRED_KEY_*)+                                            └─ FILE  payload = file bytes+```++A Sharing `Frame` is **never** framed directly on the socket: it is always the body of a+BYTES payload. See `share/QUICK_SHARE_VERIFICATION.md` for the citations.++### Handshake phases++The order is `CONNECTION_REQUEST → UKEY2 → CONNECTION_RESPONSE`, and the response is+exchanged **in plaintext by both sides**. Encryption begins only once both responses+have been seen.++| Phase | Wire body | Who sends | Citation |+|---|---|---|---|+| `Connecting` | plaintext `OfflineFrame` `CONNECTION_REQUEST` | initiator | `p000\dnsi.java:9582` |+| `Ukey2` | plaintext `Ukey2Message` × 3 | client, server, client | `p000\dnij.java:92-107`, `:176-180` |+| `ConnectionAccept` | plaintext `OfflineFrame` `CONNECTION_RESPONSE` | **both**, independently | `p000\dncj.java:1204` (written before `mo63639c()` at `:1208`) |+| `PairedKey` | encrypted `PAIRED_KEY_ENCRYPTION` + `PAIRED_KEY_RESULT` | both | see §6 |+| `Ready` | encrypted `INTRODUCTION` / `RESPONSE` / payloads | both | — |++The initiator writes the request and its UKEY2 ClientInit **back to back** without+waiting: GMS does the same (`p000\dnsi.java:9582` then `:9633` = `startClient`), and a+responder that answers the request before UKEY2 makes a real peer try to parse the+response as a `Ukey2Message`. Encryption is installed exactly where+`evaluateConnectionResult` installs it — after both sides accept+(`p000\dnsi.java:4319`, gate at `:4327-4339`).++Accepting at this layer is **programmatic**, not a user prompt: Quick Share calls+`acceptConnection` as soon as the connection is offered (`p000\dzuj.java:76`). The+user-facing accept is the Sharing-layer `INTRODUCTION` / `RESPONSE`, i.e. `nativeAccept`.  ## 3. Session lifecycle (call order)  ```-handle = nativeInit(localName, localEndpointInfo)   // 1. create session (queues ClientInit via ukey2_connections Initiator)+// isInitiator: true for the side that dialled the TCP socket, false for the acceptor.+// The initiator sends CONNECTION_REQUEST, is the UKEY2 client, and therefore speaks+// first in the response exchange too, so getting this wrong deadlocks the handshake.+handle = nativeInit(localName, localEndpointInfo, localEndpointId, isInitiator) loop {   bytes = tcpSocket.read()                           // blocking read   if (bytes != null) nativeFeedInbound(handle, bytes)+  while ((rec = nativeDrainReceived(handle)) != null) appendToFile(rec)   // §6 layout   while ((out = nativeDrainOutbound(handle)) != null) tcpSocket.write(out)   // drive UI from nativeQueryState / nativeQueryPendingFiles }-nativeAccept(handle, userAccepted, destDir)          // when state == AWAITING_ACCEPT-// during TRANSFERRING, per file:++// Sending:+nativeSetFilesToSend(handle, filesJson)              // stage metadata+nativeQueueIntroduction(handle)                      // held until the paired-key phase ends+// once state == TRANSFERRING, per file: nativeOpenFile(handle, name, size); nativeWriteChunk(handle, chunk)*; nativeCloseFile(handle)++// Receiving:+nativeAccept(handle, userAccepted, destDir)          // when state == AWAITING_ACCEPT+// destDir is vestigial: Rust never touches the filesystem, and Kotlin stages received+// bytes itself from nativeDrainReceived.++// Diagnosing:+reason = nativeQueryFailureReason(handle)            // null while healthy++nativeSendKeepAlive(handle)                          // optional, for long idle transfers nativeDestroy(handle)                                // always (finally / onCleared) -// BLE discovery (Everyone/public, no Google certs):-advBytes = nativeBuildPresenceAdvert(deviceName)     // 1. build GATT 0xFCF1 service-data (np_adv UnencryptedEncoder V0, includes version header)-advertise(advBytes)                                  //    addServiceData(ParcelUuid 0000fcf1-..., advBytes)-jsonBytes = nativeParsePresenceAdvert(serviceData)   // 2. parse scanned service-data -> JSON utf8-// jsonBytes decodes to {"deviceName":"Pixel 7","deviceType":1,"txPower":0,"isTruncated":false}-// or via alias: deviceName = nativeParsePresenceAdvertName(serviceData)+// Discovery: one endpoint id and one endpoint info for the whole device, shared by all+// three of the BLE advertisement, the mDNS record and CONNECTION_REQUEST.+type  = nativeMdnsServiceType()                      // "_FC9F5ED42C8A._tcp"+ei    = nativeBuildEndpointInfo(deviceName, DEVICE_TYPE_PHONE)+sd    = nativeBuildBleAdvertisement(ei, deviceToken, fast = false)+advertise(sd)                                        // addServiceData(0000FEF3-..., sd)+wlsi  = nativeBuildWifiLanServiceInfo(endpointId)    // 8 bytes -> Base64 instance name+registerService(base64(wlsi), txt = { "n": base64(ei), "IPv4": addr }, port)+info  = nativeParseBleAdvertisement(scannedServiceData)  // null = not ours+peer  = nativeParseEndpointInfo(info)                // null = a real device would drop it ``` +`nativeDrainReceived` must be called after **every** `nativeFeedInbound`: Rust drops each+chunk as it hands it over, so an undrained chunk is a lost chunk.+ Errors are returned as negative `int` codes from the `native* -> int` methods; a null-`byte[]` from `drainOutbound` / `queryPendingFiles` / `parsePresenceAdvert` means "nothing / no session / invalid advert".+`byte[]`/`String` from `drainOutbound` / `queryPendingFiles` / the discovery helpers means+"nothing, no session, or not parseable".  ## 4. State machine @@ -60,11 +141,11 @@ Errors are returned as negative `int` codes from the `native* -> int` methods; a  | Code | Name             | Meaning | |------|------------------|---------|-| 0 | `Handshaking`     | BetoCore UKEY2 D2D in progress (Initiator ClientInit → Server ServerInit → ClientFinished) then GCM-SIV; keep pumping bytes. |-| 1 | `AwaitingAccept`  | Introduction decoded; UI should surface `queryPendingFiles` and prompt Accept/Reject. |-| 2 | `Transferring`    | Accepted; file bytes are flowing (use `openFile`/`writeChunk`/`closeFile`). |-| 3 | `Completed`       | All files transferred + secure-message closed cleanly. |-| 4 | `Failed`          | Handshake/auth/decrypt failure or user rejected. |+| 0 | `Handshaking`     | `CONNECTION_REQUEST`/`RESPONSE`, UKEY2, and the paired-key exchange are in progress; keep pumping bytes. |+| 1 | `AwaitingAccept`  | An `INTRODUCTION` decoded; the UI should surface `queryPendingFiles` and prompt Accept/Reject. |+| 2 | `Transferring`    | Accepted; payload bytes are flowing (`openFile`/`writeChunk`/`closeFile`). |+| 3 | `Completed`       | Every announced payload arrived. |+| 4 | `Failed`          | Protocol failure, peer rejection, or local rejection. |  ## 5. JNI surface (exact signatures) @@ -72,73 +153,194 @@ Class: `com.vayunmathur.share.protocol.ShareNative` Rust symbols: `Java_com_vayunmathur_share_protocol_ShareNative_<method>` (`extern "system"`).  ```kotlin-object ShareNative {-  external fun nativeInit(localName: String, localEndpointInfo: ByteArray): Long+internal object ShareNative {+  external fun nativeInit(localName: String, localEndpointInfo: ByteArray, localEndpointId: String, isInitiator: Boolean): Long   external fun nativeFeedInbound(handle: Long, bytes: ByteArray): Int   external fun nativeDrainOutbound(handle: Long): ByteArray?         // null = nothing to send   external fun nativeQueryState(handle: Long): Int                   // State code, -1 = bad handle   external fun nativeQueryPendingFiles(handle: Long): ByteArray?     // JSON utf8, see §6   external fun nativeAccept(handle: Long, accept: Boolean, destDir: String): Int+  external fun nativeSetFilesToSend(handle: Long, json: ByteArray): Int   // same JSON shape as §6+  external fun nativeQueueIntroduction(handle: Long): Int+  external fun nativeSendKeepAlive(handle: Long): Int   external fun nativeOpenFile(handle: Long, fileName: String, fileSize: Long): Int   external fun nativeWriteChunk(handle: Long, chunk: ByteArray): Int   external fun nativeCloseFile(handle: Long): Int+  external fun nativeDrainReceived(handle: Long): ByteArray?    // one §6 record, null = none+  external fun nativeQueryFailureReason(handle: Long): String?  // null = healthy   external fun nativeDestroy(handle: Long)                           // void -  // Presence (BetoCore np_adv, Everyone/public, GATT 0xFCF1) — pure functions, no handle-  external fun nativeBuildPresenceAdvert(deviceName: String): ByteArray?   // null on error; else version header + DEs for addServiceData(0xFCF1, bytes)-  external fun nativeParsePresenceAdvert(serviceData: ByteArray): ByteArray? // null on invalid advert; else JSON utf8 {"deviceName","deviceType","txPower","isTruncated"}-  external fun nativeParsePresenceAdvertName(advertBytes: ByteArray): String? // convenience alias: display name or null+  // Discovery — derived in ble_adv.rs from SHA-256("NearbySharing"). Pure functions.+  external fun nativeMdnsServiceType(): String?                      // "_FC9F5ED42C8A._tcp"+  external fun nativeBleServiceIdHash(): ByteArray?                  // FC 9F 5E+  external fun nativeBuildBleAdvertisement(data: ByteArray, deviceToken: ByteArray, fast: Boolean): ByteArray?+  external fun nativeParseBleAdvertisement(serviceData: ByteArray): ByteArray?  // null = not ours+  external fun nativeFastInitiationServiceData(metadata: ByteArray): ByteArray? // FC128E ‖ metadata++  // Endpoint info + WifiLanServiceInfo — endpoint_info.rs. Raw bytes; Kotlin does Base64.+  external fun nativeBuildEndpointInfo(deviceName: String, deviceType: Int): ByteArray?+  external fun nativeParseEndpointInfo(blob: ByteArray): ByteArray?  // JSON utf8, null = invalid+  external fun nativeBuildWifiLanServiceInfo(endpointId: String): ByteArray?    // 8 bytes+  external fun nativeParseWifiLanServiceInfo(raw: ByteArray): ByteArray?        // JSON utf8++  // Nearby Presence — retained but NOT on the Quick Share path. See §7.+  external fun nativeBuildPresenceAdvert(deviceName: String): ByteArray?+  external fun nativeParsePresenceAdvert(serviceData: ByteArray): ByteArray?+  external fun nativeParsePresenceAdvertName(advertBytes: ByteArray): String? } ``` -Kotlin also ships `ShareSession` (`share/protocol/ShareSession.kt`) as the+Kotlin also ships `ShareSession` (`share/domain/protocol/ShareSession.kt`) as the `AutoCloseable` wrapper (handle lifetime, JSON decode, `ShareState` mapping) — the preferred call site for app code. Direct `ShareNative` calls are allowed but-`ShareSession` should be used for lifecycle correctness.-Presence helpers are called directly on `ShareNative` (no session handle); callers must tolerate `null` and fall back to BT name.+`ShareSession` should be used for lifecycle correctness. The discovery helpers are called+directly on `ShareNative` (no session handle); callers must tolerate `null`.  ## 6. Data formats -- **Bytes:** All wire frames are opaque `byte[]`. Kotlin does no framing; Rust-  is responsible for varint length-prefix around each `Ukey2Message` / `SecureMessage` / SharingFrame / `PayloadTransferFrame`, protobuf via `prost`/`protobuf` through BetoCore, and buffering-  partial reads internally. D2D secure messages are AES-256-GCM-SIV (AEAD, no separate HMAC), per-direction seq, via `D2DConnectionContextV1::encode_message_to_peer` / `decode_message_from_peer` (associated_data `None`).-- **`queryPendingFiles`:** UTF-8 JSON `byte[]` — `[{"name":"photo.jpg","sizeBytes":1234,"mimeType":"image/jpeg"}]`.-  Empty list is `[]` or (contextually) the skeleton may return a stub; rustdev-  must populate real Introduction metadata before shipping.-- **`parsePresenceAdvert`:** UTF-8 JSON `byte[]` — `{"deviceName":"Pixel 7","deviceType":1,"txPower":0,"isTruncated":false}` (`deviceType` per `np_adv::shared_data::DeviceType`: 0 Unknown, 1 Phone, 2 Tablet, 3 Display, 4 Laptop, 5 TV, 6 Watch, 7 ChromeOS, 8 Foldable, 9 Automotive, 10 Speaker). `null` on invalid/encrypted advert; Kotlin should ignore. `parsePresenceAdvertName` returns `String` display name directly.-- **Presence advert bytes:** V0 unencrypted, `UnencryptedEncoder`, `DeviceInfo` (Phone, 5..9 byte name + truncation bit) + `TxPower` (0 dBm). Version header `0x00` for V0. UUID `0000fcf1-0000-1000-8000-00805f9b34fb` (little-endian on wire `[0xF1,0xFC]`). Constructed in `share/src/main/rust/src/presence.rs` via `np_adv::AdvBuilder`.-- **Files:** Kotlin opens the destination file (SAF/MediaStore/app-cache as-  appropriate) and Rust streams decrypted payload bytes via `writeChunk`. The-  current skeleton `nativeOpenFile`/`nativeWriteChunk`/`nativeCloseFile` are-  placeholders that ack — rustdev should wire them to the secure-message decryptor-  and return `<0` on auth failure.-- **Errors:** `nativeFeedInbound` / `nativeAccept` / `native*File` return `0` on-  success, `<0` on error (`-1` bad handle/args, `-2` wrong state, etc.). The-  caller should transition to `Failed` and surface the error.--## 7. What rustdev implemented (P1 BetoCore)+- **Bytes:** all wire frames are opaque `byte[]`. Kotlin does no framing. Rust applies a+  **4-byte big-endian int32 length prefix** to every message on the socket — the UKEY2+  handshake messages and, once the channel is encrypted, every `OfflineFrame` — and it+  buffers partial reads internally. Peer-supplied lengths are bounded before allocation.+- **Secure channel:** the UKEY2 record protocol is **`AES_256_CBC-HMAC_SHA256`** with a+  per-direction sequence number, via+  `D2DConnectionContextV1::encode_message_to_peer` / `decode_message_from_peer`+  (`associated_data` `None`). GMS rejects any other record protocol outright, so this is+  not a tunable.+- **Frame nesting:** see the diagram in §2. A Sharing `Frame` is always the body of a BYTES+  payload inside `PAYLOAD_TRANSFER`; file bytes are FILE payloads split into 16 KiB+  `PayloadChunk`s with `FLAG_LAST` on the final one. The header is repeated on every chunk.+- **Paired key:** after the `CONNECTION_RESPONSE` exchange both sides must exchange+  `PAIRED_KEY_ENCRYPTION` and `PAIRED_KEY_RESULT` before the introduction. `:share` holds+  no contact certificate, so it sends a 72-byte random `signed_data` and a 6-byte random+  `secret_id_hash` — the exact widths GMS uses when signing fails — and answers+  `PAIRED_KEY_RESULT{UNABLE}`. Skipping this makes the peer time out after roughly five+  seconds.+- **`CONNECTION_RESPONSE`:** `status` (field 1) is `0` to accept and `8004` to reject+  (`p000\dncj.java:1204`, `:1622`), and `response` (field 3) is `1 = ACCEPT`,+  `2 = REJECT` (`p000\dnlx.java:1041-1051`). Both are written. `status = 0` is emitted+  **explicitly**: with field 3 absent, `p000\dnsi.java:6911` reads a merely-defaulted+  status as a rejection.+- **Endpoint info** (`nativeBuildEndpointInfo` / `nativeParseEndpointInfo`). The Nearby+  Sharing blob a peer needs to list us, minimum 17 bytes:+  `header(1) ‖ salt(2) ‖ encryptedMetadataKey(14) ‖ nameLen(1) ‖ name(1..32) ‖ TLVs*`, where+  the header is `version` in bits 7..5 (we write 1), the contact-only flag in bit 4 (we+  write 0 so the plaintext name follows) and `deviceType` in bits 3..1. Names longer than 32+  bytes are truncated on a UTF-8 boundary, since the peer rejects a name that decodes to+  U+FFFD. The metadata key is 16 random bytes: Everyone mode never needs it to decrypt to+  anything. Cited in full in `share/QUICK_SHARE_VERIFICATION.md`.+- **`WifiLanServiceInfo`** (`nativeBuildWifiLanServiceInfo` / `nativeParseWifiLanServiceInfo`).+  The mDNS instance name, exactly 8 bytes:+  `(version << 5) | pcp` with `version = 1` and `pcp = 3`, then the 4 ASCII endpoint-id+  bytes, then the 3-byte service-id hash `FC 9F 5E`. The trailing UWB-address and flags+  bytes are optional and deliberately omitted. Rust returns raw bytes; Kotlin Base64s them+  with `URL_SAFE or NO_PADDING or NO_WRAP`, which is the flag GMS passes.+- **One identity per device.** The same endpoint id and the same endpoint-info blob must go+  into the BLE advertisement, the mDNS record (instance name and `n` TXT) **and**+  `nativeInit`'s `localEndpointId` / `localEndpointInfo`, because the peer matches+  `CONNECTION_REQUEST` against what it discovered and hangs up otherwise. Renaming the+  device changes the blob, so it must be rebuilt and re-advertised.+- **`queryPendingFiles` / `setFilesToSend`:** UTF-8 JSON `byte[]` —+  `[{"name":"photo.jpg","sizeBytes":1234,"mimeType":"image/jpeg"}]`. An empty list is `[]`.+  `sizeBytes` must be a plain non-negative integer.+- **`drainReceived` record.** One decrypted FILE `PayloadChunk`, self-describing, all+  integers big-endian:++  ```+  u8   version = 1+  i64  payload_id+  i64  offset        (within the payload)+  i64  total_size    (the payload's announced length)+  u8   flags         (bit 0 = last chunk of this payload)+  u16  name_len+  u8[] name          (UTF-8)+  u32  body_len+  u8[] body+  ```++  BYTES payloads are Sharing frames, handled inside Rust, and never appear here. Rust+  keeps no copy of the body, so memory is constant in the file size — and an undrained+  chunk is lost.+- **Where received files go.** Kotlin appends each record to+  `filesDir/received/<name>` (`ReceivedFileStore`) and closes the file on the last-chunk+  flag. Nothing is written to public storage: `:share` declares no storage permission.+  The only exits are **Share** (system chooser over a `FileProvider` URI) and **Save**+  (copy into a directory the user picks with `OpenDocumentTree`, via `DocumentsContract`).+- **`BleAdvertisement` service-data:** header byte+  `(version<<5) | (socketVersion<<2) | (fast?2:0) | (rx?1:0)` with version and socket+  version both 2, then — in extended mode — the 3-byte `serviceIdHash` `FC 9F 5E`, a 4-byte+  big-endian data length, the data, and an optional 2-byte device token. Fast mode omits the+  hash and uses a single length byte, within a 27-byte total budget. Built and parsed in+  `share/src/main/rust/src/ble_adv.rs`; advertised under+  `0000FEF3-0000-1000-8000-00805F9B34FB`. The `data` payload is the endpoint-info blob+  below, and a peer that cannot parse it discards the whole advertisement.+- **`parsePresenceAdvert`:** UTF-8 JSON `byte[]` —+  `{"deviceName":"Pixel 7","deviceType":1,"txPower":0,"isTruncated":false}` (`deviceType`+  per `np_adv::shared_data::DeviceType`). Retained but unused by discovery; see §7.+- **Files:** Kotlin owns both ends of the filesystem — it reads outgoing files and stages+  incoming ones — while Rust owns chunk sequencing, offsets and payload-id bookkeeping.+  Received payloads are keyed by the `payload_id` announced in the `INTRODUCTION`.+- **Errors:** `nativeFeedInbound` / `nativeAccept` / `native*File` return `0` on success and+  `<0` on error (`-1` bad handle or args, `-2` wrong state or protocol failure). The caller+  should transition to `Failed` and surface `nativeQueryFailureReason`, which names the+  phase that broke.++## 7. Implementation map  Inside `share/src/main/rust/src/`: -- `presence.rs` — `np_adv` V0 `AdvBuilder<UnencryptedEncoder>` build + `deserialize_advertisement` + `CredentialBookBuilder<EmptyMatchedCredential>` parse (Everyone/public only, no LDT).-- `frame.rs` — varint/length-prefix + `prost` Sharing WireFormat / `PayloadTransferFrame` (tags verified vs `nearby_clone/sharing/proto/wire_format.proto` and `offline_wire_formats.proto`), keep varint helpers, 16 KiB `FLAG_LAST`.-- `session.rs` — BetoCore `D2DHandshakeContext` (Initiator/Server via `ukey2_connections`, `HandshakeImplementation::Spec`, `NextProtocol::Aes256GcmSiv`, `crypto_provider_default::CryptoProviderImpl` rustcrypto) → `D2DConnectionContextV1` AES-256-GCM-SIV encode/decode (varint-framed `SecureMessage` protobuf), adapted `frame.rs`/`payload.rs` Introduction / `ConnectionResponse` / `PayloadTransferFrame` over the new context.-- Deleted `handshake.rs` (hand-rolled P-256/commitment/HKDF UKEY2) and `secure.rs` (AES-256-CBC + HMAC) — full drop, no fallbacks.+- `frame.rs` — 4-byte big-endian framing with a sanity bound, plus the `prost` definitions+  for the Sharing wire format (`Frame` → `V1Frame` → oneof, `FileMetadata`,+  `TextMetadata`, `WifiCredentialsMetadata`, `AppMetadata`, `ConnectionResponseFrame`,+  `PairedKey*`) and the Nearby Connections wire format (`OfflineFrame` → `V1Frame` →+  `ConnectionRequest` / `ConnectionResponse` / `PayloadTransfer` / `KeepAlive` /+  `Disconnection`). **Every field carries a `p000\*.java` citation** naming the decompiled+  class it was recovered from.+- `payload.rs` — frame builders (introduction with `payload_id`/`use_case`/`start_transfer`,+  accept/reject, paired-key decoys, connection request/response, keep-alive), the BYTES vs+  FILE payload split, and chunking.+- `session.rs` — the five-phase state machine (`Connecting` → `Ukey2` →+  `ConnectionAccept` → `PairedKey` → `Ready`) over `ukey2_connections` with+  `HandshakeImplementation::Spec`, `NextProtocol::Aes256CbcHmacSha256` and+  `crypto_provider_default::CryptoProviderImpl`, plus the received-chunk queue.+- `ble_adv.rs` — the `BleAdvertisement` byte codec (extended and fast mode, with their+  length budgets) and the `SHA-256("NearbySharing")` derivations for the mDNS service type+  and the BLE `serviceIdHash`.+- `endpoint_info.rs` — the Nearby Sharing endpoint-info blob and the `WifiLanServiceInfo`+  mDNS instance name, both build and parse, with golden-byte tests. These are what make a+  device *listed*; see §6 and `share/QUICK_SHARE_VERIFICATION.md`.+- `presence.rs` — `np_adv` V0 unencrypted build/parse. **Retained but not on the Quick Share+  path**: Presence is a separate subsystem advertising under `0xFCF1`, BetoCore's+  credential/D2D/payload FFI has no Java callers in GMS 26.24.34, and whether betocore is+  live for Quick Share at all could not be determined. Discovery uses `ble_adv.rs`. -Existing JNI names/contract in `lib.rs` kept stable (init/feed/drain/query/accept/open/write/close/destroy); added `nativeBuildPresenceAdvert` / `nativeParsePresenceAdvert` (`ByteArray?` JSON) + `nativeParsePresenceAdvertName` (`String?` alias).+Ground truth and the list of corrected defects live in+`share/QUICK_SHARE_VERIFICATION.md`. There is no `nearby_clone` checkout and no `.proto`+file anywhere in this claim chain — the tags come from the decompiled protobuf-lite schema.  ## 8. What appdev must implement  - `MainActivity` + Compose screens (using `:library:ui` — direct   `androidx.compose.material*` imports are banned by lint) for:-  discovery/teaming (BLE + NSD/mDNS), nearby list, incoming banner (Accept/Reject),+  discovery/teaming (BLE + mDNS), nearby list, incoming banner (Accept/Reject),   progress, and completion. Wire `ShareSession` in a `ViewModel` (one session per peer).-- TCP transport: listen on ephemeral port, advertise via BLE/NSD, connect to peer,-  pump `feedInbound`/`drainOutbound` on a background dispatcher, post state to UI via-  `queryState` polling or callbacks.-- BLE discovery: build via `nativeBuildPresenceAdvert(deviceName)` → `addServiceData(0xFCF1, bytes)`, scan via `nativeParsePresenceAdvert(serviceData): ByteArray?` JSON or `nativeParsePresenceAdvertName: String?`, tolerate `null`.-- File I/O: destination directory picker (SAF), creating file entries, `openFile`/-  `writeChunk`/`closeFile` sequence during `Transferring`.+- TCP transport: listen on an ephemeral port, advertise via BLE/mDNS, connect to a peer,+  pump `feedInbound`/`drainOutbound` on a background dispatcher, post state to the UI via+  `queryState` polling. The dialling side must construct its session with+  `isInitiator = true` and the accepting side with `false`.+- BLE/mDNS discovery: build one endpoint-info blob with `nativeBuildEndpointInfo(...)` and+  use it everywhere. Register under `nativeMdnsServiceType()` with the Base64+  `nativeBuildWifiLanServiceInfo(endpointId)` as the instance name, the Base64 blob in the+  `n` TXT attribute and the local address in `IPv4`; advertise+  `nativeBuildBleAdvertisement(blob, token, fast)` under `0xFEF3`, preferring extended+  advertising because a full-length blob does not fit a legacy advertisement; scan with+  `setLegacy(false)` and filter with `nativeParseBleAdvertisement` then+  `nativeParseEndpointInfo` (null from either means "not a Quick Share advertiser, or one a+  real device would drop"). Optionally beacon `0xFE2C` FastInitiation. Only the mDNS leg+  yields a connectable host/port.+- File I/O: `ReceivedFileStore` stages incoming payloads in app-private storage from+  `nativeDrainReceived`; the UI offers Share and Save per file. On the send side,+  `openFile`/`writeChunk`/`closeFile` during `Transferring`. - Foreground service `ShareTransferService` for transfers that outlive the Activity. - Permissions flow: `NEARBY_WIFI_DEVICES` / `BLUETOOTH_*` / `ACCESS_FINE_LOCATION`   (see `AndroidManifest.xml`), and the `ACTION_SEND` / `ACTION_SEND_MULTIPLE`
share/QUICK_SHARE_VERIFICATION.md
diff --git a/share/QUICK_SHARE_VERIFICATION.md b/share/QUICK_SHARE_VERIFICATION.mdnew file mode 100644index 0000000000..1669371fc1--- /dev/null+++ b/share/QUICK_SHARE_VERIFICATION.md@@ -0,0 +1,438 @@+# Quick Share verification — `:share` against GMS 26.24.34++This document records **both sides** of every wire-format claim `:share` makes: what our+code does, and the decompiled GMS code that says it should. It exists because the previous+version of this module cited a source that does not exist and attributed invented constants+to "GMS-analysis findings". Anything here that is a guess is labelled a guess.++## Sources++| Name | Location | Notes |+|---|---|---|+| Decompile | `C:\Users\Vayun\gms-analysis\jadx-out-stable\sources\` | jadx output of `com.google.android.gms@[email protected]`. All `p000\xxxx.java` paths below are relative to this. |+| Writeup | `C:\Users\Vayun\gms-analysis\QUICK_SHARE_INTERNALS.md` | Prose analysis derived from the decompile. Cited as "writeup §N". Where it disagrees with the decompile, **the decompile wins** — see [Corrections](#corrections-to-the-writeup). |++There is **no** `nearby_clone` checkout on this machine. `frame.rs` and+`PROTOCOL_CONTRACT.md` previously claimed the tags were "verified against+`nearby_clone/sharing/proto/wire_format.proto`". They were not; that path never existed.++## How protobuf tags were recovered++protobuf-lite keeps a machine-readable schema in each generated class. The recipe:++1. Fields are declared in field-number order, `bitField0_` (java field `b`) first.+2. `new jeqn(DEFAULT, "<info>", new Object[]{…})` inside `mo127gY` carries the field+   **numbers and types** in the info string and the field **names** in the object array,+   in the same order. Non-string entries in the array are enum verifiers or nested+   message classes and do not consume a field slot.+3. The info string header is+   `flags, fieldCount, oneofCount, hasBitsCount, minFieldNumber, maxFieldNumber, entryCount, mapFieldCount, repeatedFieldCount, checkInitialized`,+   then one entry per field: `fieldNumber, typeChar, hasBitIndex`. The low byte of+   `typeChar` is the `FieldType` ordinal (`0 DOUBLE … 8 STRING, 9 MESSAGE, 10 BYTES,+   11 UINT32, 12 ENUM, … 18+ *_LIST, 27 MESSAGE_LIST, 35+ *_LIST_PACKED, 50 MAP,+   51+ ONEOF_*`).+4. **Types** come from the Java field declarations; **proto2 defaults** come from the+   private constructor.+5. **Semantic names** come from the Kotlin mappers, which preserve them in+   `kddz.m172584e(x, "getFoo(...)")` literals (`kddz.m172585f/e` is+   `Intrinsics.checkNotNullParameter/checkNotNullExpressionValue`).++Worked example — `FileMetadata`, `p000\duvq.java:89`:++```+info    "\u0001\t\u0000\u0001\u0001\t\t\u0000\u0000\u0000"+        + "\u0001ဈ\u0000" "\u0002᠌\u0001" "\u0003ဂ\u0002" "\u0004ဂ\u0003" "\u0005ဈ\u0004"+        + "\u0006ဂ\u0005" "\u0007ဈ\u0006" "\bဂ\u0007" "\tဇ\b"+objects {bits, "c", "d", duvo, "e", "f", "g", "h", "i", "j", "k"}+```++9 fields numbered 1..9. `ဈ`=0x1008→STRING, `᠌`=0x180C→ENUM, `ဂ`=0x1002→INT64,+`ဇ`=0x1007→BOOL. Java declares `c:String, d:int, e:long, f:long, g:String =+"application/octet-stream", h:long, i:String, j:long, k:boolean`. Names from the mapper+`p000\dzra.java` (`"getType(...)"`, `"getMimeType(...)"`, `"getParentFolder(...)"`, and+the `(id, payloadId, …)` constructor order which reads `h` then `e`). Result: the table in+[Sharing wire format](#sharing-wire-format).++## Transport, discovery and crypto++| Fact | Value | Our code | GMS |+|---|---|---|---|+| Socket framing | 4-byte **big-endian int32** length prefix, then that many bytes | `frame.rs` `frame_with_length` / `try_consume_frame` | write `p000\dnhn.java:218-221` (`writeInt`, `write`, `flush`); read `:344` (`readInt`), `:362` (`readFully`), accounting `len + 4` at `:223`/`:367` |+| Length sanity bound | reject negative, reject `> MAX_FRAME_LEN` | `frame.rs` `ConsumeResult::Invalid` | `p000\dnhn.java:348-349` (`readInt >= 0 && readInt <= jwky.m158405ae()`) |+| Applies to | UKEY2 messages **and** every encrypted frame, same channel | `session.rs` `Phase` | `p000\dnij.java:102-107` writes all three UKEY2 messages via the same `mo62623A`; `p000\dnhn.java:212` encrypts before the prefix, `:372` decrypts after it |+| Post-handshake body | an `OfflineFrame` | `session.rs` `handle_encrypted_frame` | `p000\dnhn.java:377` parses the decrypted bytes with `dnlx.m62950a` and reads an `ivlt` frame type |+| UKEY2 record protocol | **`AES_256_CBC-HMAC_SHA256`**, strictly enforced | `session.rs` `NEXT_PROTOCOL` | offered `p000\jgzt.java:798`; anything else rejected with alert 103 `"Incorrect next protocol"` at `:550-551` |+| Handshake cipher offered | ordinal `101` only | vendored `ukey2_connections` decides | `p000\jgzr.java:12` (`f505123b = 101`) |+| Nearby Connections service id | `"NearbySharing"` | `ble_adv.rs` `SERVICE_ID` | `p000\dzqx.java:108`, `:143`, `:150` |+| mDNS service type | `_%s._tcp` with `%s` = uppercase hex of `SHA-256(serviceId)[0..6]` → **`_FC9F5ED42C8A._tcp`** | `ble_adv.rs` `mdns_service_type`, asserted by `mdns_service_type_matches_gms` | `p000\dsmo.java:119-121`, `:180`; `drwj.m66219Z` = SHA-256 then `Arrays.copyOf`; `blqe.m21076e` with the uppercase alphabet at `blqe.java:8` |+| mDNS TXT | `IPv4` attribute holds the address; attributes round-trip verbatim | `NsdDiscoveryManager.kt` `TXT_IPV4` | read preference `p000\dsmo.java:127-134`; set `:550`; round-trip `:288-301` |+| BLE service UUID | **`0000FEF3-0000-1000-8000-00805F9B34FB`**, secondary `0000FC73-…` | `BleDiscoveryManager.kt` `NEARBY_CONNECTIONS_SERVICE_UUID` | `p000\dses.java:21`, `:22`; GATT-server variant `:20`; usage `p000\dsbl.java:167`, `:455-480`, `:871-876` |+| BLE `serviceIdHash` | `SHA-256("NearbySharing")[0..3]` → `FC9F5E` | `ble_adv.rs` `ble_service_id_hash` | 3-byte width enforced at `p000\dscb.java:44`, `:86` |+| BLE advertisement layout | header `(version<<5)&0xE0 \| (socketVersion<<2)&0x1C \| (fast?2:0) \| (rx?1:0)`; if not fast a 3-byte `serviceIdHash`; length 1 byte if fast else 4-byte BE; data; optional 2-byte `deviceToken` | `ble_adv.rs` `BleAdvertisement` | serialise `p000\dscb.java:126-146`; parse `p000\dsdu.java:239-297`; version/socketVersion must both be 2 (`dscb.java:56-68`, `dsdu.java:242-247`) |+| BLE advertisement budget | 27 B fast / 512 B extended | `ble_adv.rs` `MAX_FAST_ADV_LEN` / `MAX_EXTENDED_ADV_LEN` | `p000\dscb.java:116-123` |+| FastInitiation | service UUID `0xFE2C`, service-data prefix `FC128E` | `ble_adv.rs` `fast_initiation_service_data`, `BleDiscoveryManager.kt` `FAST_INITIATION_SERVICE_UUID` | `p000\dvyf.java:10`, `:34-38`; advertised `p000\dvys.java:288-295` |+| Paired-key handshake | mandatory frame pair, after the `CONNECTION_RESPONSE` exchange | `session.rs` `enter_paired_key` | writeup §11.3; signature over `roleByte ‖ authToken` at `p000\dzvh.java:233` |+| Role domain separation | signer `SENDER→1, RECEIVER→2` | not applicable (we sign nothing) | `p000\dzux.java:15-24`; role names `p000\dzur.java:14-17` |+| `secret_id_hash` decoy | **6 random bytes** | `payload.rs` `SECRET_ID_HASH_LEN` | `p000\dzvh.java:243` (`ebuk.m70456c(6)`), same width as the real `ebuk.m70455b(token, secretId, 6)` at `p000\dzux.java:7-13` |+| `signed_data` decoy | **72 random bytes** | `payload.rs` `SIGNED_DATA_DECOY_LEN` | `p000\dzkz.java:509`, `:522`, `:528` all return `m69683E(72)` when signing fails |++## Connection handshake ordering++The order is `CONNECTION_REQUEST → UKEY2 → CONNECTION_RESPONSE`, the response is+exchanged **in plaintext by both sides**, and encryption starts only once both have+accepted. Four independent sites agree:++| Fact | Citation |+|---|---|+| The client writes `CONNECTION_REQUEST` and then **immediately** starts the UKEY2 client, waiting for nothing | `p000\dnsi.java:9582` (`"In requestConnection(), wrote ConnectionRequestFrame to endpoint %s"`) then `:9633` (`dnij.m62692c` = `startClient`) |+| The server reads `CONNECTION_REQUEST` and starts the UKEY2 server, sending no response | `p000\dnsi.java:5106` (parsed `ivkl`) then `:5129` (`dnij.m62693d` = `startServer`) |+| All three UKEY2 messages go over the same framed channel, unencrypted | `p000\dnij.java:92-107` (`startClient` writes msg 1, reads 2, writes 3 via `mo62623A`/`mo62628F`), `:175-180` (`startServer`) |+| `CONNECTION_RESPONSE` is written **inside** `acceptConnection`, after UKEY2 and before the encryptor exists | `p000\dncj.java:1204-1205`, with `doeqVar.mo63639c()` only at `:1208` |+| The encryptor is installed only once **both** sides have accepted | `p000\dnsi.java:4319` (`evaluateConnectionResult`), early return at `:4327-4339`, install at `:4370`/`:4375` |+| Accepting at this layer is programmatic, not a user prompt | `p000\dzuj.java:76` calls `acceptConnection(endpointId, payloadCallback)` and awaits it with a resolution timeout; the user-facing accept is the Sharing-layer `INTRODUCTION`/`RESPONSE` |++`ConnectionResponseFrame`'s two status fields are now fully recovered, and GMS writes+**both** from one builder (`p000\dnlx.java:1031-1051`, `m62960k`):++| Field | Accept | Reject | Citation |+|---|---|---|---|+| 1 `status:int32` | `0` | `8004` | `p000\dncj.java:1204` (`m62960k(0, …)`), `:1622` (`m62960k(8004, …)`); the same `8004` `evaluateConnectionResult` reports at `p000\dnsi.java:4383` |+| 3 `response:enum` | `1` | `2` | written as `(status == 0 ? 2 : 3) - 1` at `p000\dnlx.java:1041-1051`; read back as accepted when `ivkn.m131628a(response) == 2` at `p000\dnsi.java:6911`, and `m131628a` maps `0→1, 1→2, 2→3` (`p000\ivkn.java`) |++Field 1's **presence** is load-bearing. `p000\dnsi.java:6911` reads acceptance as+`has(response) ? verify(response) == 2 : has(status) && status == 0`, so a response with+neither field — or with `status = 0` merely defaulted rather than written — is a+*rejection*. `payload.rs` therefore emits `08 00` explicitly, and+`OfflineConnectionResponseFrame::accepted()` applies the same rule when reading.++## Sharing wire format++`sharing/proto/wire_format.proto` equivalent.++| Message | GMS class | Fields |+|---|---|---|+| `Frame` | `p000\duvt.java:67` | `1 version:enum` (`p000\duvs.java`: `UNKNOWN_VERSION=0, V1=1`), `2 v1:message` |+| `V1Frame` | `p000\duwk.java:85` | `1 type:enum`, `2 introduction`, `3 connection_response`, `4 paired_key_encryption`, `5 paired_key_result`, `6 certificate_info` (`duvh`), `7 progress_update` (`duwd`), `8 bindings` (`duva`) |+| `V1Frame.FrameType` | `p000\duwj.java` | `UNKNOWN_FRAME_TYPE=0, INTRODUCTION=1, RESPONSE=2, PAIRED_KEY_ENCRYPTION=3, PAIRED_KEY_RESULT=4, CERTIFICATE_INFO=5, CANCEL=6, PROGRESS_UPDATE=7, BINDINGS=8` |+| `IntroductionFrame` | `p000\duvw.java:93` | `1 file_metadata[]`, `2 text_metadata[]`, `3 required_package:string`, `4 wifi_credentials_metadata[]`, `5 app_metadata[]`, `6 start_transfer:bool`, `8 use_case:enum`, `9 repeated int64` (unpacked) |+| `IntroductionFrame.use_case` | `p000\duvv.java` | `UNKNOWN=0, NEARBY_SHARE=1, REMOTE_COPY=2, TAP_TO_SHARE=9, FILE_SYNC=10` |+| `FileMetadata` | `p000\duvq.java:89` | `1 name:string`, `2 type:enum`, `3 payload_id:int64`, `4 size:int64`, `5 mime_type:string = "application/octet-stream"`, `6 id:int64`, `7 parent_folder:string`, `8 hash:int64`, `9 is_sensitive_content:bool` |+| `FileMetadata.Type` | `p000\duvp.java` | `UNKNOWN=0, IMAGE=1, VIDEO=2, ANDROID_APP=3, AUDIO=4, DOCUMENT=5, CONTACT_CARD=6` |+| `TextMetadata` | `p000\duwh.java:79` | **starts at field 2**: `2 text_title:string`, `3 type:enum`, `4 payload_id:int64`, `5 size:int64`, `6 id:int64`, `7 is_sensitive_text:bool` |+| `TextMetadata.Type` | `p000\duwg.java` | `UNKNOWN=0, TEXT=1, URL=2, ADDRESS=3, PHONE_NUMBER=4` |+| `WifiCredentialsMetadata` | `p000\duwo.java` | **starts at field 2**: `2 ssid:string`, `3 security_type:enum`, `4 payload_id:int64`, `5 id:int64` |+| `…SecurityType` | `p000\duwn.java` | `UNKNOWN_SECURITY_TYPE=0, OPEN=1, WPA_PSK=2, WEP=3, SAE=4` |+| `AppMetadata` | `p000\duuy.java` | `1 app_name:string`, `2 size:int64`, `3 payload_id:repeated int64` (packed), `4 id:int64`, `5 file_name:repeated string`, `6 file_size:repeated int64` (packed), `7 package_name:string` |+| `ConnectionResponseFrame` | `p000\duvl.java:67` | `1 status:enum`, `2 map<int64, duuz>` (entry types from `p000\duvi.java`) |+| `…Frame.Status` | `p000\duvk.java` | `UNKNOWN=0, ACCEPT=1, REJECT=2, NOT_ENOUGH_SPACE=3, UNSUPPORTED_ATTACHMENT_TYPE=4, TIMED_OUT=5` |+| `PairedKeyEncryptionFrame` | `p000\duvx.java:66` | `1 signed_data:bytes`, `2 secret_id_hash:bytes`, `3 optional_signed_data:bytes`, `4 qr_code_handshake_data:bytes` |+| `PairedKeyResultFrame` | `p000\duwa.java:66` | `1 status:enum`, `2 os_type:enum` |+| `…Result.Status` | `p000\duvz.java` | `UNKNOWN=0, SUCCESS=1, FAIL=2, UNABLE=3` |+| OS type | `p000\iwkr.java` | `UNKNOWN_OS_TYPE=0, ANDROID=1, CHROME_OS=2, IOS=3, WINDOWS=4, MACOS=5` |++The `PairedKeyEncryptionFrame` field order is fixed by the mapper `p000\dzrr.java:9-23`,+which builds `dzrs(signedData, optionalSignedData, secretIdHash, qrCodeHandshakeData)`+(names from `p000\dzrs.java:133`) out of java fields `c`, `e`, `d`, `f` — that is, fields+**1, 3, 2, 4**. The declaration order is *not* the constructor order.++## Nearby Connections wire format++`offline_wire_formats.proto` equivalent.++| Message | GMS class | Fields |+|---|---|---|+| `OfflineFrame` | `p000\ivla.java` | `1 version:enum` (`p000\ivkz.java` accepts `{0,1}`), `2 v1:message` |+| `V1Frame` | `p000\ivlu.java` | `1 type`, `2 connection_request` (`ivkl`), `3 connection_response` (`ivko`), `4 payload_transfer` (`ivlo`), `5 bandwidth_upgrade_negotiation` (`ivkb`), `6 keep_alive` (`ivks`), `7 disconnection` (`ivkq`), `8 paired_key_encryption` (`ivle`), `9 authentication_message` (`ivjb`), `10 authentication_result` (`ivjc`), `11 auto_resume` (`ivji`), `12 auto_reconnect` (`ivjf`), `13 bandwidth_upgrade_retry` (`ivkf`) |+| `V1Frame.FrameType` | `p000\ivlt.java` | `UNKNOWN=0, CONNECTION_REQUEST=1, CONNECTION_RESPONSE=2, PAYLOAD_TRANSFER=3, BANDWIDTH_UPGRADE_NEGOTIATION=4, KEEP_ALIVE=5, DISCONNECTION=6, PAIRED_KEY_ENCRYPTION=7, AUTHENTICATION_MESSAGE=8, AUTHENTICATION_RESULT=9, AUTO_RESUME=10, AUTO_RECONNECT=11, BANDWIDTH_UPGRADE_RETRY=12` |+| `ConnectionRequestFrame` | `p000\ivkl.java:120` | `1 endpoint_id:string`, `2 endpoint_name:string`, `3 handshake_data:bytes`, `4 nonce:int32`, `5 mediums:repeated enum` (**unpacked**), `6 endpoint_info:bytes`, `7 medium_metadata` (`ivkw`), `8 keep_alive_interval_millis:int32`, `9 keep_alive_timeout_millis:int32`, `10 device_type:int32`, `11 device_info:bytes`, `12/13` oneof (`ivkp` / `ivlr`), `14 connections_device_type:enum`, `15` (`ivkt`) |+| `Medium` | `p000\ivkk.java` | `UNKNOWN_MEDIUM=0, MDNS=1, BLUETOOTH=2, WIFI_HOTSPOT=3, BLE=4, WIFI_LAN=5, WIFI_AWARE=6, NFC=7, WIFI_DIRECT=8, WEB_RTC=9, BLE_L2CAP=10, USB=11, WEB_RTC_NON_CELLULAR=12, AWDL=13` |+| `ConnectionResponseFrame` | `p000\ivko.java:86` | `1 status:int32`, `2 handshake_data:bytes`, `3 response:enum`, `4 os_info` (`ivld`), `5 multiplex_socket_bitmask:int32`, `7 int32`, `8` (`ivkt`), `9 int32`. **No field 6.** |+| `PayloadTransferFrame` | `p000\ivlo.java` | `1 packet_type:enum`, `2 payload_header`, `3 payload_chunk`, `4 control_message` |+| `PayloadHeader` | `p000\ivln.java` | `1 id:int64`, `2 type:enum`, `3 total_size:int64`, `4 is_sensitive:bool`, `5 file_name:string`, `6 parent_folder:string`, `7 int64` |+| `PayloadChunk` | `p000\ivlk.java` | `1 flags:int32`, `2 offset:int64`, `3 body:bytes`, `4 index:int32` |+| `KeepAliveFrame` | `p000\ivks.java` | `1 ack:bool`, `2 seq_num:**uint32**` |+| `DisconnectionFrame` | `p000\ivkq.java` | `1 bool`, `2 bool` |++`endpoint_id` and `endpoint_name` are both validated as required:+`p000\dnlx.java:669` (`"OfflineFrame CONNECTION_REQUEST missing endpointId field."`) and+`:675` (`"… missing endpointName field."`). Field vocabulary from `p000\dnlw.java:305`+(`ConnectRequestParameters{endpointId=…, endpointInfo=…, handshakeData=…, nonce=…,+mediums=…, keepAliveIntervalMillis=…, keepAliveTimeoutMillis=…, deviceType=…,+localDeviceInfo=…}`).++## Discovery: the endpoint-info blob and `WifiLanServiceInfo`++Being *listed* by a Quick Share device needs two structures that used to be listed under+[Not determinable](#not-determinable-from-the-apk). Both are fully recovered. The+obfuscated classes kept their `toString()` names: `dzqk` is+`Advertisement(version, encryptedMetadataKey, deviceType, deviceName,+qrCodeAdvertisingToken, vendorId)`, `dzrl` is `EncryptedMetadataKey(cipherText, salt)`.++**Nearby Sharing endpoint info** — builder `dzqk.m69796b()` (`p000\dzqk.java:134-186`),+parser `dzqj.m69794a()` (`p000\dzqj.java:11-92`), bit helpers `dzrm.m69822a` / `m69823b`+(`p000\dzrm.java`).++| Offset | Field | Notes |+|---|---|---|+| 0 bits 7..5 | `version` | 0 or 1 accepted (`dzqj.java:26-29`); GMS always writes 1 (`dzph.java:355`, `dzxp.java:360`, `eair.java:93`) |+| 0 bit 4 | visibility | `1` = contact-only, no name follows; `0` = plaintext name follows |+| 0 bits 3..1 | `deviceType` | `UNKNOWN=0, PHONE=1, TABLET=2, LAPTOP=3, CAR=4, FOLDABLE=5, XR=6` (`p000\eanu.java`) |+| 1..2 | `salt` | exactly 2 bytes (`p000\dzrl.java:20-23`) |+| 3..16 | `encryptedMetadataKey` | exactly 14 bytes (same check); written after the salt (`dzqk.java:150`) |+| 17 | `nameLen` | `1..32`, present only when the visibility bit is 0 (`dzqj.java:47`) |+| 18.. | `name` | UTF-8; rejected if decoding yields U+FFFD (`dzqj.java:51-54`) |+| then | TLVs | `type(1) len(1) value(len)`; `1` = QR token, `2` = 1-byte vendor id |++The parser's first check is `length < 17` →+`"Incorrect advertisement format: size (%s) is less than minimum size (%s)."`+(`dzqj.java:18-21`).++**Everyone mode needs no real metadata key.** `eafm.m70022a` (`p000\eafm.java:7-14`) looks+the credential up (`dzvb.m69877b`) and passes the result — `null` when nothing matches — to+`dzqk.m69795a`, which only bails with `"Decode contact-only mode advertisement without+credential"` when the **plaintext name is absent**. So 2 + 14 random bytes plus a plaintext+name decode fine; `endpoint_info.rs` documents them as decoys, exactly like+`SECRET_ID_HASH_LEN` / `SIGNED_DATA_DECOY_LEN` in `payload.rs`.++**`WifiLanServiceInfo`** (the mDNS instance name) — serializer `p000\dnuw.java:175-207`,+deserializer `p000\dnux.java:66-145`. The struct is URL-safe, unpadded, unwrapped Base64:+`bloa.m20888c` / `m20891f` / `m20892g` all pass Android flag `11`+(`p000\bloa.java:29`, `:53`, `:61`).++| Offset | Field | Notes |+|---|---|---|+| 0 bits 7..5 | `version` | must be 1 (`dnux.java:91-95`); written as `pcp \| 32` (`dnuw.java:176`) |+| 0 bits 4..0 | `pcp` | must be 1, 2 or 3 (`dnux.java:110-113`). Quick Share advertises `Strategy(1,1)` (`p000\dzye.java:23`), which `dnsi.m63137x` maps to **3** (`p000\dnsi.java:922`) |+| 1..4 | `endpointId` | exactly 4 ASCII bytes (`dnuw.java:179-181`) |+| 5..7 | `serviceIdHash` | `FC 9F 5E`, the same 3 bytes `ble_adv.rs` already derives |+| 8 | UWB address length | optional; `0`, `2` or `8` |+| 9 | flags | optional |++Minimum accepted length is 8 (`dnux.java:87-90`) and both trailing fields are guarded by+`wrap.remaining() > 0` (`:119`, `:134`), so `:share` emits exactly 8 bytes. That is+deliberate: the flags byte's base value (`r24` at `dnuw.java:194-199`) did not survive+decompilation, and omitting an optional field guesses nothing. If hardware testing shows+the peer wants those bytes, that is where to look.++The endpoint info also carries the peer's display name in the `n` TXT attribute+(`dnuw.java:208`, name literal `"n"`), which `dnux.java:98-106` requires.++### The same blob is required in three places++| # | Where | What the peer does without it |+|---|---|---|+| 1 | BLE `0xFEF3` `BleAdvertisement.data` | `p000\eafg.java:89-93`: parse fails → `"Failed to parse endpoint %s (%s)"` → never listed |+| 2 | mDNS `_FC9F5ED42C8A._tcp` record | `p000\dnux.java:103-105`: `"Cannot deserialize WifiLanServiceInfo: EndpointInfo is missing"` → never listed |+| 3 | `ConnectionRequestFrame.endpoint_info` | `p000\each.java:2092-2097`: `"Failed to parse incoming connection from endpoint %s. Disconnecting."` → hangs up |++Site 2 is the one that decides whether a transfer can happen at all, because **WIFI_LAN is+the only medium `:share` can accept a connection on**.++## Defects fixed++| # | Was | Is now | Severity |+|---|---|---|---|+| A | protobuf base-128 **varint** length prefix (`frame.rs` `encode_varint`/`frame_with_length`) | 4-byte big-endian int32 (`p000\dnhn.java:219`, `:344`) plus a sanity bound (`:348`) | Blocker |+| B | `NextProtocol::Aes256GcmSiv` — rejected by GMS with alert 103 | `NextProtocol::Aes256CbcHmacSha256` (`p000\jgzt.java:550`, `:798`) | Blocker |+| C | emitted a **bare** `PayloadTransferFrame`; no `OfflineFrame` wrapper, no connection phase, no keep-alive | full `OfflineFrame` layer, `CONNECTION_REQUEST`/`CONNECTION_RESPONSE` phase, `KEEP_ALIVE`; Sharing `Frame`s ride inside a BYTES `PAYLOAD_TRANSFER` | Blocker |+| D | flattened `SharingFrame` with no `Frame{version,v1}` wrapper | `SharingFrame` → `SharingV1Frame` → oneof (`p000\duvt.java`, `p000\duwk.java`) | Blocker |+| E | `FileMetadata` as `name=1, size=2, mime_type=3, type=4, id=5, payload_id=6(**string**)` | the verified 9-field layout with `payload_id=3:int64` (`p000\duvq.java:89`) | Blocker |+| F | sent `status=0` to accept and `1` to reject; accepted `0 or 1` | `ACCEPT=1` / `REJECT=2` with the other four statuses mapped to a failure reason (`p000\duvk.java`) | Blocker |+| G | `IntroductionFrame` had fields 1–3 only | fields 1–6 and 8, including `start_transfer` and `use_case` | Major |+| I | `SharingFileType::File = 5`, a name that does not exist; no `CONTACT_CARD` | `Document = 5`, `AndroidApp = 3`, `ContactCard = 6` (`p000\duvp.java`) | Major |+| J | never sent `PAIRED_KEY_ENCRYPTION` / `PAIRED_KEY_RESULT`; the stubs had one field each | mandatory pair with 6-byte and 72-byte random decoys and `PairedKeyResultStatus::Unable` | Blocker |+| K | mDNS `_up._tcp` with a random 16-byte instance name and no TXT | `_FC9F5ED42C8A._tcp` derived from the digest, a Base64 `WifiLanServiceInfo` instance name, `IPv4` and `n` TXT | Blocker |+| L | advertised/scanned `0xFCF1` with an `np_adv` V0 unencrypted advert | `0xFEF3` with a Nearby Connections `BleAdvertisement`; optional `0xFE2C` FastInitiation | Blocker |+| M | asserted verification against `nearby_clone`, which does not exist, and attributed `0xFCF1`/`_up._tcp`/`np_adv` to "GMS-analysis findings" | this document; every field in `frame.rs` carries a `p000\*.java` citation | Doc integrity |+| N | ordering inverted: `CONNECTION_REQUEST → CONNECTION_RESPONSE → UKEY2`, so our initiator **blocked** waiting for a response the peer never sends before UKEY2, and our responder answered where the peer expects UKEY2 message 1 | `CONNECTION_REQUEST → UKEY2 → CONNECTION_RESPONSE`, response plaintext from both sides, encryption starting once both accept (see [Connection handshake ordering](#connection-handshake-ordering)) | Blocker |+| O | `ConnectionResponseFrame.status` used a **guessed** `8` to reject and left field 3 unset | `0` / `8004` on field 1, `1` / `2` on field 3, both written, `status = 0` explicitly present | Blocker |+| P | received payloads accumulated into `ActiveRecv.received: Vec<u8>` with **no JNI entry point to read them** — every received file was written to memory and dropped, and a large one OOMed the process | `nativeDrainReceived` hands out one chunk at a time; `ReceivedFileStore` streams them to `filesDir/received` | Blocker |+| Q | `FileSaveHelper`, `TcpTransport.writeIncomingChunk` and `closeIncomingFile` had **zero callers**, and `writeIncomingChunk` called `session.writeChunk` — the *send* path — on received data | all three deleted; the pump drains `nativeDrainReceived` into the store | Major |+| R | `ConnectionRequestFrame` omitted `keep_alive_interval_millis` / `keep_alive_timeout_millis`, which GMS's builder always populates (`p000\dnlw.java:305`) | both set (values ours, since GMS's are Phenotype-driven) | Minor |+| S | BLE advertised the **bare UTF-8 device name** as `BleAdvertisement.data`, which fails `dzqj.java`'s 17-byte floor — a Google device discarded us before the handshake this repo had spent its effort on | a real endpoint-info blob (`endpoint_info.rs`), so `p000\eafg.java:91` parses instead of logging `"Failed to parse endpoint"` | Blocker |+| T | mDNS instance name was the raw 4-character endpoint id and `n` was the plaintext device name, so `dnux.m63241a` failed Base64-decoding the instance name and then rejected the record with `"EndpointInfo is missing"` | Base64 `WifiLanServiceInfo` instance name and Base64 endpoint info in `n` — both directions of the only medium `:share` can accept a connection on | Blocker |+| U | `ConnectionRequestFrame.endpoint_info` was **empty** (`ShareViewModel` never passed `localEndpointInfo` to `TcpTransport`) and `Session::new` generated its own `endpoint_id`, so we advertised one identity and dialled out under another | one endpoint id and one endpoint info shared by the BLE advertisement, the mDNS record and `CONNECTION_REQUEST` | Blocker |+| V | only legacy BLE advertising was reachable, and a real blob does not fit 31 bytes; the advertisement also carried a redundant `addServiceUuid` next to `addServiceData`, and the scan used a legacy-only `ScanSettings` | `startAdvertisingSet` with a fast-mode legacy fallback (`p000\dsbl.java:513`, `:624`), service data only (`:454`, `:876`), and `setLegacy(false)` on the scan (`:884`) | Blocker |+| — | a failed session surfaced only `"Protocol error (-2)"` | `nativeQueryFailureReason` surfaces the specific reason, which names the phase that broke | Minor |+| — | `session.rs` cloned the whole inbound buffer once per loop iteration to peek | `try_consume_frame` operates on `&mut self.inbound_buf` directly | Minor |+| — | received payloads were matched by `recvs.iter_mut().find(!completed)` | keyed by the `payload_id` announced in the `INTRODUCTION` | Major |+| — | `payload.rs` carried a `_touch_text_metadata` dead-code hack to keep an import alive | `TextMetadata` is genuinely defined and decoded | Minor |++Already correct before this change, and unchanged: `PayloadTransferFrame`,+`PayloadHeader` fields 1–6, `PayloadChunk` fields 1–3, and payload type+`BYTES=1, FILE=2, STREAM=3`.++## Corrections to the writeup++The writeup and the decompile disagree in two places. The decompile is primary.++1. **`TextMetadata.Type` is 1-based.** Writeup §5.3 lists+   `0=TEXT, 1=URL, 2=ADDRESS, 3=PHONE_NUMBER`. `p000\duwg.java` reads+   `UNKNOWN(0), TEXT(1), URL(2), ADDRESS(3), PHONE_NUMBER(4)`. The pre-existing `frame.rs`+   values were therefore already right and were **not** changed.+2. **`PairedKeyEncryptionFrame` field order.** The declaration order `signedData,+   optionalSignedData, secretIdHash, qrCodeHandshakeData` is the *constructor* order of+   `dzrs`, not the field order. `p000\dzrr.java:9-23` shows `secret_id_hash` is field 2 and+   `optional_signed_data` is field 3.++## Not determinable from the APK++Stated here rather than papered over.++- **Contact-based visibility is not implementable.** It needs per-contact certificates+  minted against a Google account via `nearbysharing-pa.googleapis.com` (writeup §11.7).+  `:share` is Everyone-mode only and its paired-key frames will always be decoys. That is+  why `PAIRED_KEY_RESULT` carries `UNABLE` (cannot verify) rather than `FAIL` (verified+  and rejected).+- **The `WifiLanServiceInfo` flags byte.** Its base value (`r24` at+  `p000\dnuw.java:194-199`) did not survive decompilation. The field is optional, so+  `:share` omits it and the UWB-address byte rather than guessing — see+  [Discovery](#discovery-the-endpoint-info-blob-and-wifilanserviceinfo).+- **Which mediums a given Google device will actually use.** Quick Share's enabled set+  comes from `dzyl.f204956d` via `dmyg.m61906b` (`p000\dmyg.java:14-46`, where medium `5`+  is WIFI_LAN) and is Phenotype-driven. A device with WIFI_LAN discovery disabled will find+  us over BLE and then try to connect over BLE GATT/L2CAP, which `:share` does not+  implement: it would list us and then fail at connect.+- **Bandwidth upgrade is not implemented.** `:share` rides WIFI_LAN directly; GMS+  bootstraps on BLE and then upgrades (writeup §10.6), so a peer that starts on BLE and+  expects an upgrade will not be satisfied by a LAN-only implementation.+- **UKEY2 DH curve.** Only handshake cipher ordinal `101` is observable (`p000\jgzr.java:12`,+  writeup §11.4). The vendored `ukey2_connections` chooses the curve. No comment in this+  repository asserts X25519.+- **`IntroductionFrame` field 9** (repeated int64, unpacked) exists but its meaning is not+  recovered: `p000\dzra.java` copies it into `dzrf.f204456h` only behind a `use_case`+  guard and no getter literal survives. It is not declared in `frame.rs`.+- **`MAX_FRAME_LEN`.** GMS bounds the read with the Phenotype flag+  `jwky.m158405ae()` (`p000\dnhn.java:349`), whose shipped value is server-side. The 5 MiB+  in `frame.rs` is **ours**.+- **`MAX_CHUNK`.** 16 KiB is ours too; Nearby's chunk size is Phenotype-tunable.+- **Timeouts are Phenotype-driven** (writeup §13.2), so any constant is a guess at a+  server-side value. The only shipped defaults worth honouring are the ~5 s paired-key read+  timeout and the 20 s connection timeout (writeup §9.9) — and note the stale+  `"15 seconds"` log string, which does not match the value it reports.+- **Download directory.** GMS defaults to `"Quick Share"` under public Downloads and does+  **no** `MediaStore` insert on the receive path (writeup §9.8). `:share` streams received+  files into app-private `filesDir/received` instead and lets the user Share or Save each+  one; that is a product decision, not a protocol one, and it needs no storage permission.++### Previously listed here, now recovered++- **`BleAdvertisement.data` / the Nearby Sharing endpoint-info blob.** This section used to+  say the layout "must be recovered from `p000\dzrl.java` / the sharing advertisement+  builder before BLE bootstrap can be claimed to work", and that mDNS was the path that+  worked. **Both halves of that were wrong.** The layout is fully readable — builder+  `dzqk.m69796b`, parser `dzqj.m69794a`, key widths `dzrl.java:20-23` — including the+  accept/reject semantics for a missing credential, and the mDNS record needed the *same*+  blob, so it was not working either. See+  [Discovery](#discovery-the-endpoint-info-blob-and-wifilanserviceinfo) and defects S–V.+  The same shape of mistake as the `ConnectionResponseFrame` guess below: an unrecovered+  field was written off instead of read.+- **`ConnectionResponseFrame.response` (field 3) value names.** This section used to say+  the 1/2 mapping "cannot be read out of the APK" because R8 stripped the names, and that+  `:share` would write only field 1 with an **inferred** `0` for accept and a **guessed**+  `8` for reject. The guess was wrong twice over. Both the builder+  (`p000\dnlx.java:1041-1051`) and the reader (`p000\dnsi.java:6911` with+  `p000\ivkn.java`) pin the mapping without needing the names, the reject status is+  `8004` (`p000\dncj.java:1622`), and field 1's presence is load-bearing. See+  [Connection handshake ordering](#connection-handshake-ordering).++## How this is defended++A round-trip test cannot catch a wrong tag number — it passes against any self-consistent+assignment, which is exactly why the previous suite was green against a fabricated format.+So `frame.rs` asserts **golden bytes**:++| Test | Pins |+|---|---|+| `length_prefix_is_four_byte_big_endian` | `00 00 00 0D` for 13 bytes, `00 00 01 2C` for 300 — a varint prefix would be `0D` and `AC 02` |+| `partial_read_split_mid_prefix` | buffering across a split inside the 4-byte prefix |+| `negative_and_oversized_lengths_are_rejected` | the `dnhn.java:348` bound, and that the buffer is not drained on rejection |+| `file_metadata_golden_bytes` | `0A05612E7478741005180720AC022A0A746578742F706C61696E` |+| `connection_response_accept_encodes_status_one` | `0801` for accept, `0802` for reject |+| `sharing_frame_nesting_golden_bytes` | the full `Frame{version:V1, v1:{type:INTRODUCTION, introduction:{…}}}` nesting |+| `paired_key_encryption_field_order` | `secret_id_hash` at tag `0x12`, `optional_signed_data` at tag `0x1A` |+| `connection_request_mediums_are_unpacked` | `2805`, not the packed `2A0105` |+| `text_and_wifi_metadata_start_at_field_two` | tag `0x12` for `text_title` and `ssid`, not `0x0A` |+| `mdns_service_type_matches_gms` | `_FC9F5ED42C8A._tcp` from `SHA-256("NearbySharing")[0..6]` |+| `ble_service_id_hash_is_the_first_three_digest_bytes` | `FC 9F 5E` |+| `extended_advertisement_round_trip` | header byte `0x48`, the 3-byte hash, the 4-byte BE length |+| `chunked_transfer_is_keyed_by_the_announced_payload_id` | received bytes land under the id from the `INTRODUCTION`, and reach Kotlin through `drain_received` |+| `offline_connection_response_golden_bytes` | `08 00 18 01` for accept and `08 C4 3E 18 02` for reject — both status fields, with `status = 0` present rather than defaulted |+| `a_response_with_neither_status_nor_field_three_is_a_rejection` | GMS's acceptance rule at `p000\dnsi.java:6911` |+| `received_record_layout_is_stable` | the whole `drain_received` record, byte for byte |+| `endpoint_info_golden_bytes` | header `0x22` for `version=1, visibility=0, deviceType=PHONE`, the 16 key bytes, then the length-prefixed name |+| `the_bare_device_name_is_not_a_valid_endpoint_info` | the bug this fixed cannot come back: `parse` refuses the bare UTF-8 name |+| `parse_rejects_a_blob_shorter_than_the_minimum` / `parse_rejects_a_bad_name_length` / `parse_rejects_an_invalid_utf8_name` / `parse_rejects_an_unknown_version` / `parse_rejects_a_truncated_tlv` | one named `dzqj.java` check each |+| `a_multibyte_name_round_trips_and_truncates_on_a_char_boundary` | a 32-byte cap that never splits a character, since a split one decodes to the U+FFFD `dzqj.java:51-54` rejects |+| `wifi_lan_service_info_golden_bytes` | `0x23` for `version=1, pcp=3`, the 4-byte id, `FC 9F 5E`, and exactly 8 bytes |+| `parse_wifi_lan_service_info_applies_the_gms_checks` | the length, version and PCP checks at `dnux.java:86-118` |+| `fast_mode_only_fits_a_short_endpoint_info` | why extended advertising is required: a full-length name does not fit the 27-byte fast budget |+| `the_connection_request_carries_the_advertised_identity` | the advertised endpoint id and endpoint info reach `CONNECTION_REQUEST`, instead of a second random id and an empty blob |++The previous suite was green against the **wrong ordering**, because both sides of a+round-trip test shared the mistake. These four tests would have caught it:++| Test | Pins |+|---|---|+| `initiators_first_batch_is_the_request_and_ukey2_together` | the first thing on the wire is `CONNECTION_REQUEST` **and** a message a real UKEY2 server accepts, with no `CONNECTION_RESPONSE` |+| `responder_sends_no_connection_response_until_ukey2_completes` | a responder fed only the request stays silent; the response appears only after ClientFinished |+| `connection_response_is_plaintext_and_encryption_starts_after_both` | the response round-trips as plaintext protobuf on both sides, and every frame after it does not |+| `a_rejecting_connection_response_fails_the_session_with_the_peers_status` | `8004` is read as a rejection and reported verbatim |++Plus two on the receive path: `a_streamed_payload_is_never_retained_in_the_session`+(draining as you pump empties the queue, so memory is constant in the file size) and the+record round-trip above.++## Interop status++**Ordering, wire format and discovery corrected against the decompile; interop still+unverified.**++The handshake matches GMS phase for phase, the two constants that were guessed are+recovered, and the two discovery structures that were written off as unrecoverable are now+byte-correct against the decompile. That is a decompile-level claim, not an interop result:+**nothing here has been run against a Google device**, so the reported "does not+interoperate with Quick Share" cannot be called fixed until step 2 or 3 below passes on+hardware. What changed is that discovery is no longer *known* to be broken.++Verified on the host: `cargo test -p share_nearby` (69 tests) and+`cargo check -p share_nearby --target aarch64-linux-android`. The session tests drive two+`:share` sessions through the complete+`CONNECTION_REQUEST → UKEY2 → CONNECTION_RESPONSE → PAIRED_KEY_* → INTRODUCTION → RESPONSE → PAYLOAD_TRANSFER`+sequence, which proves internal consistency — both sides share any remaining error — plus+the ordering and discovery tests above, which pin the bytes against the citations rather+than against ourselves.++Not run, because it needs physical hardware:++1. Two `:share` devices on one Wi-Fi network: send a file end to end, then exercise Share+   and Save on the receiver. Proves the whole receive path, and that the new encodings are+   at least self-consistent.+2. `:share` → a Pixel with Quick Share set to "Everyone": the Pixel must **list our device+   by its real name** — the reported bug — then show the Accept sheet with the right+   filename and size, and receive the file.+3. Pixel → `:share` in the same configuration.+4. `adb logcat -s NearbySharing` on the Pixel during 2 and 3. Per writeup §13.6 every log+   string is verbatim, so failures are diagnosable:+   `"Incorrect advertisement format: size (%s) is less than minimum size (%s)."` means the+   endpoint info is still malformed; `"Failed to parse endpoint %s (%s)"`+   (`p000\eafg.java:91`) means BLE discovery still rejects us;+   `"Cannot deserialize WifiLanServiceInfo: EndpointInfo is missing"` means the `n` TXT+   attribute is wrong; `"Failed to parse incoming connection from endpoint %s.+   Disconnecting."` (`p000\each.java:2094`) means `endpoint_info` is not reaching+   `CONNECTION_REQUEST`; `"Incorrect next protocol"` means the cipher;+   `"In readConnectionRequestFrame, expected a CONNECTION_REQUEST v1 OfflineFrame but got a+   %s frame instead"` (`p000\dnsi.java:4067`) means the ordering is still wrong; and+   `"Read an unencrypted (or garbage) frame when we expected an encrypted frame."`+   (`p000\dnhn.java:381`) means the encryption-start point is off by one exchange.++One failure mode is out of our hands: if the Google device has WIFI_LAN discovery disabled+by Phenotype it will find us over BLE and then try to connect over BLE GATT/L2CAP, which+`:share` does not implement. The signature of that case is discovery succeeding while no TCP+connection ever arrives at our `ServerSocket`. A BLE transport is out of scope.++## Unrelated note++`share/SIGNAL_VERIFICATION.md` is entirely about `communicate/**` and+`communicate/src/main/rust/src/signal.rs`. It is in the wrong module. Flagged here rather+than moved, since that is a separate change.
share/src/main/AndroidManifest.xml
diff --git a/share/src/main/AndroidManifest.xml b/share/src/main/AndroidManifest.xmlindex e2db5dd636..1791e5bdc6 100644--- a/share/src/main/AndroidManifest.xml+++ b/share/src/main/AndroidManifest.xml@@ -6,6 +6,11 @@     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />+    <!-- Local Network Protections (Android 16+): without this, NsdManager.registerService+         throws SecurityException("Missing local network permission") and every LAN socket is+         blocked. WIFI_LAN is the only medium :share can accept a transfer on, so discovery+         and transfer both depend on it. -->+    <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />      <!-- BLE discovery (Nearby Connections uses BLE for advertisement + scan) -->     <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />@@ -71,5 +76,15 @@             android:name=".platform.transfer.ShareTransferService"             android:exported="false"             android:foregroundServiceType="dataSync" />+        <!-- Grants read access to a received file when the user taps Share. -->+        <provider+            android:name="androidx.core.content.FileProvider"+            android:authorities="${applicationId}.fileprovider"+            android:exported="false"+            android:grantUriPermissions="true">+            <meta-data+                android:name="android.support.FILE_PROVIDER_PATHS"+                android:resource="@xml/file_paths" />+        </provider>     </application> </manifest>
share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.ktindex 0022532c81..78c2652636 100644--- a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt@@ -1,12 +1,31 @@ package com.vayunmathur.share.domain.protocol  import com.vayunmathur.share.protocol.ShareNative+import java.nio.ByteBuffer+import java.nio.ByteOrder import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json  @Serializable data class PendingFile(val name: String, val sizeBytes: Long, val mimeType: String) +/**+ * One decrypted chunk of an incoming FILE payload, as handed over by+ * [ShareSession.drainReceived].+ *+ * [offset] is the chunk's position within the payload and [totalSize] the payload's+ * announced length, so a caller can report progress without tracking either itself.+ * [isLast] marks the final chunk, which is when the destination file can be closed.+ */+class ReceivedChunk(+    val payloadId: Long,+    val offset: Long,+    val totalSize: Long,+    val isLast: Boolean,+    val name: String,+    val body: ByteArray,+)+ /** Transfer state — ordinal matches the Rust State enum (see PROTOCOL_CONTRACT.md §4). */ enum class ShareState(val code: Int) {     Handshaking(0),@@ -25,9 +44,17 @@ enum class ShareState(val code: Int) {  * Thin lifecycle wrapper around the native session handle. Dispatch on  * [state] in your UI (Handshaking → AwaitingAccept → Transferring → Completed/Failed).  *+ * [isInitiator] must reflect which side opened the TCP socket: `true` for the dialler,+ * `false` for the acceptor. Only the initiator sends `CONNECTION_REQUEST`, and only the+ * initiator is the UKEY2 client, so getting this wrong deadlocks the handshake.+ *+ * [localEndpointInfo] and [localEndpointId] must be the ones this device advertises: the+ * peer matches `CONNECTION_REQUEST` against what it discovered, and drops the connection+ * when either is missing or malformed.+ *  * Usage (one instance per TCP connection / peer):  * ```- * val session = ShareSession(localName = "My Phone")+ * val session = ShareSession(localName = "My Phone", isInitiator = true)  * try {  *     // after TCP connect, pump bytes:  *     session.feedInbound(socket.read())@@ -44,8 +71,11 @@ enum class ShareState(val code: Int) { class ShareSession @JvmOverloads constructor(     localName: String,     localEndpointInfo: ByteArray = ByteArray(0),+    localEndpointId: String = "",+    isInitiator: Boolean = true, ) : AutoCloseable {-    val handle: Long = ShareNative.nativeInit(localName, localEndpointInfo)+    val handle: Long =+        ShareNative.nativeInit(localName, localEndpointInfo, localEndpointId, isInitiator)     private var closed = false      /** Feed raw bytes read from the TCP socket into the protocol state machine. Returns 0 on ok. */@@ -71,6 +101,24 @@ class ShareSession @JvmOverloads constructor(     fun accept(accept: Boolean, destDir: String = ""): Int =         ShareNative.nativeAccept(handle, accept, destDir) +    /**+     * Stage the files this side will send, then announce them with [queueIntroduction].+     *+     * Safe to call at any point after construction; the announcement itself is held+     * until the paired-key exchange completes.+     */+    fun setFilesToSend(files: List<PendingFile>): Int =+        ShareNative.nativeSetFilesToSend(+            handle,+            Json.encodeToString(files).encodeToByteArray(),+        )++    /** Announce the files staged by [setFilesToSend]. */+    fun queueIntroduction(): Int = ShareNative.nativeQueueIntroduction(handle)++    /** Emit a `KEEP_ALIVE` frame so a long or idle transfer is not torn down. */+    fun sendKeepAlive(): Int = ShareNative.nativeSendKeepAlive(handle)+     fun openFile(fileName: String, fileSize: Long): Int =         ShareNative.nativeOpenFile(handle, fileName, fileSize) @@ -78,6 +126,29 @@ class ShareSession @JvmOverloads constructor(      fun closeFile(): Int = ShareNative.nativeCloseFile(handle) +    /**+     * Take the next received FILE chunk, or null when nothing is pending.+     *+     * Call in a loop after every [feedInbound]. Rust drops each chunk as it hands it+     * over, so a caller that drains as it pumps holds one chunk at a time no matter+     * how large the file is; a caller that never drains loses the bytes.+     */+    fun drainReceived(): ReceivedChunk? =+        ShareNative.nativeDrainReceived(handle)?.let(::decodeReceivedRecord)++    /**+     * Why the session failed, or null while it is healthy.+     *+     * Specific enough to diagnose a handshake against real hardware, unlike the+     * return code alone.+     */+    val failureReason: String? get() = ShareNative.nativeQueryFailureReason(handle)++    /**+     * Recent protocol events, one per line, for diagnosing a peer that stops responding.+     */+    val trace: String? get() = ShareNative.nativeQueryTrace(handle)+     fun destroy() {         if (!closed) {             closed = true@@ -87,3 +158,41 @@ class ShareSession @JvmOverloads constructor(      override fun close() = destroy() }++/**+ * Decode the received-chunk record of PROTOCOL_CONTRACT.md §6.+ *+ * ```+ * u8 version=1 | i64 payload_id | i64 offset | i64 total_size | u8 flags+ * u16 name_len | u8[] name | u32 body_len | u8[] body      // all big-endian+ * ```+ *+ * Returns null on a version or length mismatch rather than throwing: a record this+ * side cannot read is a bug in the pair, not something a transfer should crash on.+ */+private fun decodeReceivedRecord(raw: ByteArray): ReceivedChunk? {+    val buf = ByteBuffer.wrap(raw).order(ByteOrder.BIG_ENDIAN)+    return try {+        if (buf.get() != RECEIVED_RECORD_VERSION) return null+        val payloadId = buf.long+        val offset = buf.long+        val totalSize = buf.long+        val flags = buf.get().toInt()+        val name = ByteArray(buf.short.toInt() and 0xFFFF).also(buf::get).decodeToString()+        val body = ByteArray(buf.int).also(buf::get)+        ReceivedChunk(+            payloadId = payloadId,+            offset = offset,+            totalSize = totalSize,+            isLast = (flags and RECEIVED_FLAG_LAST) != 0,+            name = name,+            body = body,+        )+    } catch (_: RuntimeException) {+        // BufferUnderflowException / NegativeArraySizeException: a truncated record.+        null+    }+}++private const val RECEIVED_RECORD_VERSION: Byte = 1+private const val RECEIVED_FLAG_LAST: Int = 1
share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.ktindex dfa55609e4..81e48899c3 100644--- a/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt+++ b/share/src/main/java/com/vayunmathur/share/network/transport/TcpTransport.kt@@ -4,8 +4,9 @@ import android.util.Log import com.vayunmathur.share.domain.protocol.PendingFile import com.vayunmathur.share.domain.protocol.ShareSession import com.vayunmathur.share.domain.protocol.ShareState+import com.vayunmathur.share.platform.ReceivedFile+import com.vayunmathur.share.platform.ReceivedFileStore import java.io.File-import java.io.FileOutputStream import java.io.OutputStream import java.net.InetAddress import java.net.InetSocketAddress@@ -16,6 +17,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -27,30 +29,75 @@ private const val TAG = "TcpTransport" private const val SOCKET_TIMEOUT_MS = 30_000 private const val CONNECT_TIMEOUT_MS = 10_000 +/**+ * How long to wait for the peer's user to accept before giving up.+ *+ * Ours, not a recovered constant: GMS's own timeouts are Phenotype-driven. Long enough for+ * someone to look at the phone and tap.+ */+private const val ACCEPT_WAIT_MS = 60_000L++/**+ * Read timeout inside the pump loop.+ *+ * Short so the loop wakes often enough to send keep-alives and re-poll state, not because+ * the peer is expected to be this chatty.+ */+private const val PUMP_READ_TIMEOUT_MS = 2_000++/**+ * How often to emit `KEEP_ALIVE`, matching the interval we advertise in+ * `ConnectionRequestFrame.keep_alive_interval_millis`.+ *+ * Not optional: a peer that is told to expect keep-alives every 5 s tears the connection+ * down when they never arrive, which looks exactly like an unexplained disconnect a dozen+ * seconds into every transfer.+ */+private const val KEEP_ALIVE_EVERY_MS = 5_000L+ /**  * TCP transport pump that wires raw bytes to/from the Rust [ShareSession]  * per PROTOCOL_CONTRACT.md §3 and §6.  *  * Kotlin owns: TCP listen/connect, raw socket I/O.- * Rust owns: varint length-prefix, protobuf, secure-message, and it buffers- * partial reads internally — Kotlin does NO framing. All Rust outbound from- * [ShareSession.drainOutbound] is already varint length-prefixed (frame.rs- * frame_with_length); Kotlin writes it verbatim. Inbound bytes are fed- * verbatim via [ShareSession.feedInbound] and Rust's inbound_buf reassembly- * handles partial frames.+ * Rust owns: the 4-byte big-endian length prefix, protobuf, the D2D secure channel, and+ * partial-read buffering — Kotlin does NO framing. Everything+ * [ShareSession.drainOutbound] returns is already framed (`frame.rs frame_with_length`);+ * Kotlin writes it verbatim. Inbound bytes go in verbatim via [ShareSession.feedInbound]+ * and Rust's `inbound_buf` reassembles partial frames.  *  * Contract loop (per §3):  *   bytes = tcpSocket.read()          // raw read, blocking  *   if (bytes != null) feedInbound(handle, bytes)+ *   while ((rec = drainReceived(handle)) != null) receivedStore.append(rec)  *   while ((out = drainOutbound(handle)) != null) tcpSocket.write(out)  // raw write  *   poll state via queryState / queryPendingFiles  *- * Each peer gets its own [ShareSession] (handle lifetime owns the Rust session).+ * Each peer gets its own [ShareSession] (handle lifetime owns the Rust session). The+ * session's role follows the socket: the side that dialled is the initiator.  */ class TcpTransport(-    private val localName: String,-    private val localEndpointInfo: ByteArray = ByteArray(0),+    localName: String,+    private val receivedStore: ReceivedFileStore,+    localEndpointInfo: ByteArray = ByteArray(0),+    localEndpointId: String = "", ) {+    private var localName: String = localName+    private var localEndpointInfo: ByteArray = localEndpointInfo+    private var localEndpointId: String = localEndpointId++    /**+     * Set the identity new sessions announce, after the user renames the device.+     *+     * Must be the same identity that is being advertised over mDNS and BLE: the peer+     * matches `CONNECTION_REQUEST` against what it discovered. Sessions already running+     * keep the identity they were created with.+     */+    fun setLocalIdentity(name: String, endpointInfo: ByteArray, endpointId: String) {+        localName = name+        localEndpointInfo = endpointInfo+        localEndpointId = endpointId+    }     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)      private var serverSocket: ServerSocket? = null@@ -133,7 +180,15 @@ class TcpTransport(     }      private fun launchConnection(socket: Socket, incoming: Boolean): Connection {-        val session = ShareSession(localName, localEndpointInfo)+        // The side that dialled the socket is the Nearby Connections initiator: it sends+        // CONNECTION_REQUEST and drives UKEY2 as the client. The endpoint info and id are+        // the advertised ones, so the peer sees the identity it discovered.+        val session = ShareSession(+            localName = localName,+            localEndpointInfo = localEndpointInfo,+            localEndpointId = localEndpointId,+            isInitiator = !incoming,+        )         val conn = Connection(             socket = socket,             session = session,@@ -161,12 +216,22 @@ class TcpTransport(             val input = socket.getInputStream()             val output = socket.getOutputStream()             val buf = ByteArray(8192)+            socket.soTimeout = PUMP_READ_TIMEOUT_MS+            var lastKeepAlive = System.currentTimeMillis()+            fun keepAliveIfDue() {+                val now = System.currentTimeMillis()+                if (now - lastKeepAlive < KEEP_ALIVE_EVERY_MS) return+                lastKeepAlive = now+                session.sendKeepAlive()+                drainAll(session, output)+            }             while (isActive && !socket.isClosed) {                 val n: Int = try {                     input.read(buf)                 } catch (e: java.net.SocketTimeoutException) {                     // Periodic keep-alive: drain outbound even on read timeout so                     // handshake retries / accept responses still flush.+                    keepAliveIfDue()                     drainAll(session, output)                     conn.updateStateFromSession()                     if (conn.state.value == ShareState.Failed || conn.state.value == ShareState.Completed) break@@ -178,15 +243,18 @@ class TcpTransport(                 }                 if (n == 0) continue                 val inbound = buf.copyOf(n)+                Log.d(TAG, "IN  ${hexPrefix(inbound)}")                 conn.bytesReceived.value += n                 val rc = session.feedInbound(inbound)                 if (rc < 0) {                     Log.w(TAG, "feedInbound failed rc=$rc")-                    conn.error.value = "Protocol error ($rc)"+                    conn.error.value = session.failureReason ?: "Protocol error ($rc)"                     conn.state.value = ShareState.Failed                     break                 }+                drainReceived(conn)                 drainAll(session, output)+                keepAliveIfDue()                 conn.updateStateFromSession()                 if (conn.state.value == ShareState.Completed || conn.state.value == ShareState.Failed) break             }@@ -198,7 +266,8 @@ class TcpTransport(             } catch (_: Exception) {             }         } finally {-            // Graceful shutdown: one last drain.+            // Graceful shutdown: one last drain in each direction.+            drainReceived(conn)             try {                 drainAll(session, socket.getOutputStream())             } catch (_: Exception) {@@ -207,15 +276,48 @@ class TcpTransport(                 socket.close()             } catch (_: Exception) {             }+            receivedStore.closeSession(session.handle)             conn.updateStateFromSession()         }     } +    /**+     * Move every chunk Rust has decrypted into the staging store, publishing a+     * [ReceivedFile] as each payload completes.+     *+     * Must run after every [ShareSession.feedInbound]: Rust drops each chunk as it+     * hands it over, so an undrained chunk is a lost chunk.+     */+    private fun drainReceived(conn: Connection) {+        val session = conn.session+        while (true) {+            val chunk = session.drainReceived() ?: return+            val finished = receivedStore.append(session.handle, chunk) ?: continue+            val announcedMime = conn.pendingFiles.value+                .firstOrNull { it.name == chunk.name }+                ?.mimeType+                ?.takeIf { it.isNotBlank() }+            conn.receivedFiles.value += ReceivedFile(+                name = finished.name,+                sizeBytes = finished.length(),+                mimeType = announcedMime ?: ReceivedFileStore.mimeTypeOf(finished),+                uri = receivedStore.contentUri(finished),+            )+            Log.i(TAG, "received ${finished.name} (${finished.length()} bytes)")+        }+    }++    /** TEMP DIAGNOSTIC: hex of a frame prefix, for comparing our SecureMessage headers to the peer's. */+    private fun hexPrefix(bytes: ByteArray, n: Int = 96): String =+        bytes.take(n).joinToString("") { "%02x".format(it) } ++            if (bytes.size > n) "…(${bytes.size}B)" else "(${bytes.size}B)"+     private fun drainAll(session: ShareSession, out: OutputStream) {         while (true) {             val bytes = session.drainOutbound() ?: break-            // Rust already varint length-prefixed each frame and concatenated them;-            // write verbatim — Kotlin does no framing per PROTOCOL_CONTRACT.md §6.+            Log.d(TAG, "OUT ${hexPrefix(bytes)}")+            // Rust already applied the 4-byte big-endian length prefix to each frame and+            // concatenated them; write verbatim per PROTOCOL_CONTRACT.md §6.             out.write(bytes)             out.flush()         }@@ -229,7 +331,8 @@ class TcpTransport(             pendingFiles.value = session.pendingFiles         }         if (polled == ShareState.Failed) {-            if (error.value == null) error.value = "Transfer failed"+            if (error.value == null) error.value = session.failureReason ?: "Transfer failed"+            Log.w(TAG, "session ${session.handle} failed: ${error.value}\n${session.trace}")         }     } @@ -239,6 +342,7 @@ class TcpTransport(             conn.socket.close()         } catch (_: Exception) {         }+        receivedStore.closeSession(conn.session.handle)         try {             conn.session.destroy()         } catch (_: Exception) {@@ -263,6 +367,7 @@ class TcpTransport(             }             connections.clear()         }+        receivedStore.closeAll()         _incomingConnections.value = emptyList()         scope.cancel()     }@@ -272,13 +377,39 @@ class TcpTransport(     // ------------------------------------------------------------------      /**-     * Send the given [files] over [conn]'s session. Must only be called when-     * conn is in Handshaking/AwaitingAccept so the Introduction + payload-     * exchange can kick in. The actual wire bytes are handled by the session-     * pump; this helper stages OPEN/WRITE/CLOSE sequence and updates progress.+     * Send the given [files] over [conn]'s session.+     *+     * Stages the metadata, announces it with an `INTRODUCTION` (held by Rust until the+     * paired-key exchange finishes), waits for the peer to accept, then streams each+     * file. The payload ids the peer sees come from the introduction, so the bytes match+     * the metadata it showed the user.      */     suspend fun sendFiles(conn: Connection, files: List<File>) = withContext(Dispatchers.IO) {         val session = conn.session+        val staged = files.map {+            PendingFile(name = it.name, sizeBytes = it.length(), mimeType = "")+        }+        if (session.setFilesToSend(staged) < 0 || session.queueIntroduction() < 0) {+            conn.error.value = "Failed to announce files"+            conn.state.value = ShareState.Failed+            return@withContext+        }+        drainAll(session, conn.socket.getOutputStream())+        // Wait for the peer to accept before streaming a single chunk. Rust flips to+        // Transferring when the Sharing ConnectionResponse arrives; a real device hangs up+        // if payload chunks show up for a transfer its user has not accepted yet, and+        // openFile refuses with -2 in that state anyway.+        val deadline = System.currentTimeMillis() + ACCEPT_WAIT_MS+        while (isActive && conn.state.value != ShareState.Transferring) {+            conn.updateStateFromSession()+            if (conn.state.value == ShareState.Failed) return@withContext+            if (System.currentTimeMillis() > deadline) {+                conn.error.value = "peer never accepted the transfer"+                conn.state.value = ShareState.Failed+                return@withContext+            }+            delay(100)+        }         for (file in files) {             if (!isActive) break             val rc = session.openFile(file.name, file.length())@@ -312,12 +443,13 @@ class TcpTransport(     }      /**-     * Receive files for an incoming connection — called after [ShareSession.accept]-     * has transitioned the session to Transferring. Buffers inbound payload bytes-     * into [destDir].+     * Answer the peer's `INTRODUCTION`.+     *+     * Received bytes go to app-private staging via [ReceivedFileStore], so there is no+     * destination to choose here; the user picks one later, per file, with Save.      */-    fun acceptIncoming(conn: Connection, destDir: File, accept: Boolean): Int {-        val rc = conn.session.accept(accept, destDir.absolutePath)+    fun acceptIncoming(conn: Connection, accept: Boolean): Int {+        val rc = conn.session.accept(accept)         if (rc < 0) {             conn.error.value = "accept failed ($rc)"             return rc@@ -331,51 +463,6 @@ class TcpTransport(         }         return rc     }--    /** Write a chunk from the peer (payload path) into [destDir]/filename. */-    fun writeIncomingChunk(-        conn: Connection,-        destDir: File,-        fileName: String,-        fileSize: Long,-        chunk: ByteArray,-        currentOut: FileOutputStream?,-    ): FileOutputStream? {-        var out = currentOut-        if (out == null) {-            conn.session.openFile(fileName, fileSize)-            destDir.mkdirs()-            val dest = File(destDir, fileName).let { f ->-                // Avoid clobbering.-                if (!f.exists()) f else {-                    var i = 1-                    var cand: File-                    do {-                        val dot = fileName.lastIndexOf('.')-                        val base = if (dot >= 0) fileName.substring(0, dot) else fileName-                        val ext = if (dot >= 0) fileName.substring(dot) else ""-                        cand = File(destDir, "${base}_$i$ext")-                        i++-                    } while (cand.exists())-                    cand-                }-            }-            out = FileOutputStream(dest)-        }-        // Pass through Rust decryptor.-        conn.session.writeChunk(chunk)-        out.write(chunk)-        conn.bytesReceived.value += chunk.size-        return out-    }--    fun closeIncomingFile(conn: Connection, out: FileOutputStream?) {-        try {-            out?.close()-        } catch (_: Exception) {-        }-        conn.session.closeFile()-    } }  /**@@ -390,10 +477,10 @@ class Connection(     var pumpJob: Job? = null     val state: MutableStateFlow<ShareState> = MutableStateFlow(ShareState.Handshaking)     val pendingFiles: MutableStateFlow<List<PendingFile>> = MutableStateFlow(emptyList())++    /** Files that finished arriving, each staged in app-private storage. */+    val receivedFiles: MutableStateFlow<List<ReceivedFile>> = MutableStateFlow(emptyList())     val bytesSent: MutableStateFlow<Long> = MutableStateFlow(0L)     val bytesReceived: MutableStateFlow<Long> = MutableStateFlow(0L)     val error: MutableStateFlow<String?> = MutableStateFlow(null)--    /** Derived PIN/verification code for the transfer — surfaced once Introduction is decoded. */-    val verificationCode: String? get() = null // Rust will expose a PIN when implemented; wire it via nativeQueryPin or pendingFiles extra. }
share/src/main/java/com/vayunmathur/share/platform/FileSaveHelper.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/FileSaveHelper.kt b/share/src/main/java/com/vayunmathur/share/platform/FileSaveHelper.ktdeleted file mode 100644index 8ee513e906..0000000000--- a/share/src/main/java/com/vayunmathur/share/platform/FileSaveHelper.kt+++ /dev/null@@ -1,141 +0,0 @@-package com.vayunmathur.share.platform--import android.content.ContentValues-import android.content.Context-import android.os.Build-import android.os.Environment-import android.provider.MediaStore-import java.io.File-import java.io.InputStream--/**- * Persists received files to the user-visible storage location.- *- * Strategy:- *  - On API 29+ (scoped storage), insert into MediaStore.Downloads / MediaStore.Images etc- *    based on MIME, falling back to a "Share" subdirectory in Downloads.- *  - On API < 29 or when MediaStore insertion fails, write under- *    context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)/Share which remains- *    visible via the downloads/file-manager on most devices.- *- * The received file bytes are streamed by [com.vayunmathur.share.network.transport.TcpTransport];- * once a file is completely written to a staging [File], hand it here to promote it- * to the public location and return its public [android.net.Uri].- */-object FileSaveHelper {--    fun saveToDownloads(context: Context, stagingFile: File, displayName: String, mimeType: String): File {-        return promoteToPublic(context, stagingFile, displayName, mimeType)-    }--    /**-     * Copy [input] to the public Share directory entry for [displayName].-     * Returns the public file handle; the caller is responsible for closing [input].-     */-    fun saveStreamToDownloads(-        context: Context,-        input: InputStream,-        displayName: String,-        mimeType: String,-    ): File {-        val staging = File(context.cacheDir, "share_incoming/$displayName")-        staging.parentFile?.mkdirs()-        staging.outputStream().use { out -> input.copyTo(out) }-        return promoteToPublic(context, staging, displayName, mimeType)-    }--    private fun promoteToPublic(context: Context, staging: File, displayName: String, mimeType: String): File {-        // Prefer MediaStore on Q+; fallback to app-external dir so file manager can find it.-        val saved = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {-            trySaveViaMediaStore(context, staging, displayName, mimeType)-        } else null-        if (saved != null) {-            // Also delete staging; MediaStore copy is canonical.-            try {-                staging.delete()-            } catch (_: Exception) {-            }-            return saved-        }-        val destDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)-            ?.let { File(it, "Share") }-            ?: File(context.filesDir, "Share")-        destDir.mkdirs()-        val dest = uniqueFile(destDir, displayName)-        try {-            staging.copyTo(dest, overwrite = false)-            staging.delete()-        } catch (_: Exception) {-            // If copy failed, at least expose staging itself.-            return staging-        }-        return dest-    }--    private fun trySaveViaMediaStore(-        context: Context,-        staging: File,-        displayName: String,-        mimeType: String,-    ): File? {-        val resolver = context.contentResolver-        val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {-            MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)-        } else null ?: return null-        val mime = mimeType.ifBlank { "application/octet-stream" }-        val values = ContentValues().apply {-            put(MediaStore.Downloads.DISPLAY_NAME, displayName)-            put(MediaStore.Downloads.MIME_TYPE, mime)-            put(MediaStore.Downloads.IS_PENDING, 1)-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {-                put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/Share")-            }-        }-        val uri = resolver.insert(collection, values) ?: return null-        return try {-            resolver.openOutputStream(uri)?.use { out ->-                staging.inputStream().use { input -> input.copyTo(out) }-            }-            values.clear()-            values.put(MediaStore.Downloads.IS_PENDING, 0)-            resolver.update(uri, values, null, null)-            // Return a file handle pointing to the MediaStore location's cached path if available.-            // Consumers that need a Uri should query Downloads; we return staging-like path via resolver query.-            // As a convenience, try to resolve the _data column; if unavailable, return staging.-            var path: String? = null-            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {-                resolver.query(uri, arrayOf(MediaStore.Downloads.DATA), null, null, null)?.use { c ->-                    if (c.moveToFirst()) {-                        path = c.getString(0)-                    }-                }-            }-            if (path != null) File(path!!) else run {-                // Return a sentinel file representing the MediaStore entry.-                File(context.cacheDir, "share_mediastore_uri.txt").also {-                    it.writeText(uri.toString())-                }-            }-        } catch (e: Exception) {-            try {-                resolver.delete(uri, null, null)-            } catch (_: Exception) {-            }-            null-        }-    }--    private fun uniqueFile(dir: File, name: String): File {-        var file = File(dir, name)-        if (!file.exists()) return file-        var i = 1-        while (file.exists()) {-            val dot = name.lastIndexOf('.')-            val base = if (dot >= 0) name.substring(0, dot) else name-            val ext = if (dot >= 0) name.substring(dot) else ""-            file = File(dir, "${base}_$i$ext")-            i++-        }-        return file-    }-}
share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.ktnew file mode 100644index 0000000000..cd30227918--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt@@ -0,0 +1,132 @@+package com.vayunmathur.share.platform++import android.content.Context+import android.net.Uri+import android.webkit.MimeTypeMap+import androidx.core.content.FileProvider+import com.vayunmathur.share.domain.protocol.ReceivedChunk+import java.io.File+import java.io.FileOutputStream++/**+ * Staging area for incoming files, under app-private `filesDir/received`.+ *+ * Received bytes deliberately do **not** land in public storage. `:share` declares no+ * storage permission, and writing where the user did not ask is worse than making them+ * choose: the UI offers Share (system chooser) and Save (a directory they pick), and+ * those are the only ways a received file leaves this directory.+ *+ * One [FileOutputStream] stays open per in-flight payload, keyed by session as well as+ * payload id because ids are only unique within a session. Streams are opened on the+ * first chunk and closed on the last, so nothing is buffered in memory.+ */+class ReceivedFileStore(private val context: Context) {++    private class Open(val file: File, val stream: FileOutputStream)++    private val lock = Any()+    private val open = mutableMapOf<Pair<Long, Long>, Open>()++    private val dir: File get() = File(context.filesDir, "received")++    /**+     * Append [chunk] to its file, returning the completed [File] on the last chunk and+     * null otherwise. Returns null on an I/O failure, having closed the stream.+     */+    fun append(sessionKey: Long, chunk: ReceivedChunk): File? {+        val key = sessionKey to chunk.payloadId+        synchronized(lock) {+            val entry = open[key] ?: openFor(key, chunk.name) ?: return null+            return try {+                entry.stream.write(chunk.body)+                if (!chunk.isLast) return null+                entry.stream.close()+                open.remove(key)+                entry.file+            } catch (_: Exception) {+                closeQuietly(entry.stream)+                entry.file.delete()+                open.remove(key)+                null+            }+        }+    }++    private fun openFor(key: Pair<Long, Long>, name: String): Open? {+        dir.mkdirs()+        val safeName = name.replace('/', '_').replace('\\', '_').ifBlank { "received_file" }+        val file = uniqueFile(dir, safeName)+        return try {+            Open(file, FileOutputStream(file)).also { open[key] = it }+        } catch (_: Exception) {+            null+        }+    }++    /**+     * Abandon any streams still open for [sessionKey], e.g. on disconnect.+     *+     * A partly written file is deleted: nothing publishes it, resuming is not+     * implemented, so leaving it would only fill the data directory with fragments no+     * one can reach.+     */+    fun closeSession(sessionKey: Long) {+        synchronized(lock) {+            val keys = open.keys.filter { it.first == sessionKey }+            keys.forEach { key ->+                open.remove(key)?.let { entry ->+                    closeQuietly(entry.stream)+                    entry.file.delete()+                }+            }+        }+    }++    fun closeAll() {+        synchronized(lock) {+            open.values.forEach {+                closeQuietly(it.stream)+                it.file.delete()+            }+            open.clear()+        }+    }++    /**+     * A content URI another app can read, granted per-intent.+     *+     * The authority is derived from the package name so it stays correct across build+     * variants, matching the other two call sites in the repo (`notes`, `files`).+     */+    fun contentUri(file: File): Uri =+        FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)++    private fun closeQuietly(stream: FileOutputStream) {+        try {+            stream.close()+        } catch (_: Exception) {+        }+    }++    companion object {+        /** MIME type for [file] from its extension, for the share chooser. */+        fun mimeTypeOf(file: File): String =+            MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())+                ?: "application/octet-stream"++        /** `report.pdf` -> `report_1.pdf` when the name is taken. */+        fun uniqueFile(dir: File, name: String): File {+            var file = File(dir, name)+            if (!file.exists()) return file+            val dot = name.lastIndexOf('.')+            val base = if (dot >= 0) name.substring(0, dot) else name+            val ext = if (dot >= 0) name.substring(dot) else ""+            var i = 1+            while (file.exists()) {+                file = File(dir, "${base}_$i$ext")+                i+++            }+            return file+        }+    }+}
share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt b/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.ktindex 91e18a12dc..9fdec5785e 100644--- a/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/SharePermissions.kt@@ -18,6 +18,15 @@ object SharePermissions {     /** Wi-Fi Direct / Hotspot transport (Android 13+ shows a dedicated dialog). */     val NEARBY_WIFI = Manifest.permission.NEARBY_WIFI_DEVICES +    /**+     * Local Network Protections (Android 16+). Gates mDNS *and* every LAN socket, so+     * without it `NsdManager.registerService` throws+     * `SecurityException("Missing local network permission")` and `:share` is invisible+     * over WIFI_LAN — the only medium it can accept a transfer on.+     */+    val LOCAL_NETWORK =+        if (Build.VERSION.SDK_INT >= 36) Manifest.permission.ACCESS_LOCAL_NETWORK else null+     /** Foreground-service notification (Android 13+). */     val POST_NOTIFICATIONS = if (Build.VERSION.SDK_INT >= 33) Manifest.permission.POST_NOTIFICATIONS else null @@ -31,6 +40,7 @@ object SharePermissions {         add(NEARBY_WIFI)         add(FINE_LOCATION)         add(COARSE_LOCATION)+        LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray() @@ -41,6 +51,7 @@ object SharePermissions {         add(NEARBY_WIFI)         add(FINE_LOCATION)         add(COARSE_LOCATION)+        LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray() @@ -51,6 +62,7 @@ object SharePermissions {         add(NEARBY_WIFI)         add(FINE_LOCATION)         add(COARSE_LOCATION)+        LOCAL_NETWORK?.let { add(it) }         POST_NOTIFICATIONS?.let { add(it) }     }.toTypedArray() }
share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.ktindex a23f809921..9c793a1650 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt@@ -1,5 +1,6 @@ package com.vayunmathur.share.platform +import android.content.Context import android.net.Uri import com.vayunmathur.share.platform.discovery.NearbyDevice import com.vayunmathur.share.domain.protocol.PendingFile@@ -31,9 +32,23 @@ data class SendUiState(     val hasPermissions: Boolean = true, ) +/**+ * A file that finished arriving and is staged in app-private storage.+ *+ * [uri] is a `FileProvider` content URI, so it can be handed to another app without a+ * storage permission. The file stays where it is until the user shares or saves it.+ */+data class ReceivedFile(+    val name: String,+    val sizeBytes: Long,+    val mimeType: String,+    val uri: Uri,+)+ data class TransferProgress(     val state: ShareState,     val pendingFiles: List<PendingFile>,+    val receivedFiles: List<ReceivedFile>,     val bytesSent: Long,     val bytesReceived: Long,     val error: String?,@@ -42,6 +57,7 @@ data class TransferProgress( fun Connection.toProgress(): TransferProgress = TransferProgress(     state = state.value,     pendingFiles = pendingFiles.value,+    receivedFiles = receivedFiles.value,     bytesSent = bytesSent.value,     bytesReceived = bytesReceived.value,     error = error.value,@@ -57,6 +73,17 @@ interface ShareActions {     fun clearOutgoing()     fun disconnect(connection: Connection) +    /**+     * Hand [file] to the system share chooser.+     *+     * Takes a [Context] because launching an Activity needs one that belongs to a task;+     * pass the composable's `LocalContext`, not an application context.+     */+    fun shareReceivedFile(context: Context, file: ReceivedFile)++    /** Copy [file] into [treeUri], a directory the user picked with `OpenDocumentTree`. */+    fun saveReceivedFile(file: ReceivedFile, treeUri: Uri)+     companion object {         val Noop = object : ShareActions {             override fun setVisible(visible: Boolean) {}@@ -67,6 +94,8 @@ interface ShareActions {             override fun setOutgoingUris(uris: List<Uri>) {}             override fun clearOutgoing() {}             override fun disconnect(connection: Connection) {}+            override fun shareReceivedFile(context: Context, file: ReceivedFile) {}+            override fun saveReceivedFile(file: ReceivedFile, treeUri: Uri) {}         }     } }
share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.ktindex ed686f5505..3f9cf3e518 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -5,12 +5,17 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build+import android.provider.DocumentsContract import android.provider.OpenableColumns import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.share.BuildConfig+import com.vayunmathur.share.R import com.vayunmathur.share.platform.discovery.BleDiscoveryManager import com.vayunmathur.share.platform.discovery.DiscoverySource import com.vayunmathur.share.platform.discovery.NearbyDevice@@ -18,6 +23,7 @@ import com.vayunmathur.share.platform.discovery.NsdDiscoveryManager import com.vayunmathur.share.domain.protocol.PendingFile import com.vayunmathur.share.domain.protocol.ShareState import com.vayunmathur.share.platform.transfer.ShareTransferService+import com.vayunmathur.share.protocol.ShareNative import com.vayunmathur.share.network.transport.Connection import com.vayunmathur.share.network.transport.TcpTransport import java.io.File@@ -37,12 +43,17 @@ private const val TAG = "ShareVM" /**  * Single ViewModel for the Share app (Receive + Send).  *- * BetoCore model (Everyone / public identity only):- *  - Visibility: ServerSocket(0) on WiFi-LAN -> register _up._tcp with random 16-byte ServiceId- *    and the ephemeral port, + BLE Nearby Presence advert under GATT 0xFCF1 whose bytes come from- *    the Rust np_adv JNI (presence-derived device name, no plaintext endpoint_info on mDNS).- *  - Discovery: browse _up._tcp (resolves host/port) + scan 0xFCF1 (presence name), then merge- *    by endpointId; connect requires host/port from the _up._tcp leg.+ * Everyone-mode only (no Google account, so no contact certificates):+ *  - Visibility: `ServerSocket(0)` on WIFI_LAN, its port registered under+ *    `_FC9F5ED42C8A._tcp` (the service type derived from `SHA-256("NearbySharing")`),+ *    plus a Nearby Connections `BleAdvertisement` under GATT `0xFEF3`.+ *  - Discovery: browse `_FC9F5ED42C8A._tcp` (resolves host/port) and scan `0xFEF3`, then+ *    merge by endpointId. Connecting needs host/port, which only the mDNS leg supplies.+ *+ * One endpoint id and one endpoint-info blob are shared by the BLE advertisement, the mDNS+ * record and `CONNECTION_REQUEST`. A peer matches the request against what it discovered,+ * so a device that advertises one identity and dials out under another is hung up on+ * (`p000\each.java:2092-2097`).  */ class ShareViewModel(     application: Application,@@ -58,7 +69,11 @@ class ShareViewModel(     val localName: StateFlow<String> = _localName.asStateFlow()      fun setLocalName(name: String) {-        _localName.value = name.trim().ifBlank { _localName.value }+        val trimmed = name.trim().ifBlank { return }+        if (trimmed == _localName.value) return+        _localName.value = trimmed+        // The name is inside the endpoint-info blob, so renaming means re-advertising.+        if (_isVisible.value) setVisible(true)     }      // --- Subsystems (lazy so the VM can be constructed in previews / tests@@ -66,8 +81,37 @@ class ShareViewModel(      private val nsd by lazy { NsdDiscoveryManager(appContext) }     private val ble by lazy { BleDiscoveryManager(appContext) }-    // TcpTransport owns ServerSocket(0) on WiFi-LAN; NsdDiscoveryManager publishes its port under _up._tcp.-    private val transport by lazy { TcpTransport(localName = _localName.value) }+    private val receivedStore by lazy { ReceivedFileStore(appContext) }+    // TcpTransport owns ServerSocket(0) on WIFI_LAN; NsdDiscoveryManager publishes its port.+    private val transport by lazy {+        TcpTransport(+            localName = _localName.value,+            receivedStore = receivedStore,+            localEndpointInfo = endpointInfo() ?: ByteArray(0),+            localEndpointId = localEndpointId,+        )+    }++    /**+     * Endpoint id advertised as the mDNS instance name. Nearby endpoint ids are four+     * characters; a stable random one per process keeps re-advertising idempotent.+     */+    private val localEndpointId: String by lazy {+        val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+        (1..4).map { alphabet.random() }.joinToString("")+    }++    /**+     * The endpoint-info blob for the current device name, or null if it cannot be built.+     *+     * PHONE is cosmetic — it picks the icon the peer renders next to our name.+     */+    private fun endpointInfo(): ByteArray? = try {+        ShareNative.nativeBuildEndpointInfo(_localName.value, ShareNative.DEVICE_TYPE_PHONE)+    } catch (e: UnsatisfiedLinkError) {+        Log.e(TAG, "libshare_nearby unavailable — cannot build endpoint info", e)+        null+    }      // --- Receive: visibility toggle ------------------------------------- @@ -99,15 +143,26 @@ class ShareViewModel(     }      override fun setVisible(visible: Boolean) {-        _isVisible.value = visible         if (visible) {+            val endpointInfo = endpointInfo()+            if (endpointInfo == null) {+                Log.w(TAG, "cannot advertise without an endpoint info blob")+                _isVisible.value = false+                return+            }+            _isVisible.value = true+            // Before listen(), so a socket accepted immediately announces the identity we+            // are about to advertise rather than the transport's construction-time one.+            transport.setLocalIdentity(localName.value, endpointInfo, localEndpointId)             val port = transport.listen()-            // Register _up._tcp with a random 16-byte ServiceId, publishing the WiFi-LAN port.-            nsd.advertise(localName.value, port)-            // BLE Nearby Presence advert under 0xFCF1 (bytes from Rust np_adv JNI, public mode).-            ble.startAdvertising(localName.value)+            // Publish the WIFI_LAN port under _FC9F5ED42C8A._tcp, with the endpoint info in+            // the `n` TXT attribute — the record a Quick Share device lists us from.+            nsd.advertise(localEndpointId, endpointInfo, port)+            // The same blob inside a Nearby Connections BleAdvertisement under 0xFEF3.+            ble.startAdvertising(localEndpointId, endpointInfo)             ShareTransferService.startReceiveMode(appContext, port)         } else {+            _isVisible.value = false             nsd.unadvertise()             ble.stopAdvertising()             transport.stopListening()@@ -117,14 +172,61 @@ class ShareViewModel(      override fun acceptIncoming(connection: Connection, accept: Boolean) {         viewModelScope.launch(Dispatchers.IO) {-            val destDir = File(appContext.getExternalFilesDir(null), "Share/Received").also { it.mkdirs() }-            val rc = transport.acceptIncoming(connection, destDir, accept)+            val rc = transport.acceptIncoming(connection, accept)             if (rc < 0) {                 Log.w(TAG, "acceptIncoming failed rc=$rc")             }         }     } +    override fun shareReceivedFile(context: Context, file: ReceivedFile) {+        ExternalIntents.shareFile(+            context = context,+            uri = file.uri,+            mimeType = file.mimeType,+            chooserTitle = context.getString(R.string.share_received_chooser),+        )+    }++    override fun saveReceivedFile(file: ReceivedFile, treeUri: Uri) {+        viewModelScope.launch(Dispatchers.IO) {+            val saved = copyIntoTree(file, treeUri)+            AppMessages.show(+                appContext.getString(+                    if (saved) R.string.share_save_succeeded else R.string.share_save_failed,+                    file.name,+                )+            )+        }+    }++    /**+     * Copy [file] into the SAF tree [treeUri] the user picked.+     *+     * Uses the platform [DocumentsContract] rather than `androidx.documentfile`, which+     * is not a dependency of this repo. `createDocument` may hand back a different+     * display name than requested if one is taken; that is the provider's call, not+     * ours, so nothing here second-guesses it.+     */+    private fun copyIntoTree(file: ReceivedFile, treeUri: Uri): Boolean = try {+        val resolver = appContext.contentResolver+        val parent = DocumentsContract.buildDocumentUriUsingTree(+            treeUri,+            DocumentsContract.getTreeDocumentId(treeUri),+        )+        val target = DocumentsContract.createDocument(resolver, parent, file.mimeType, file.name)+        if (target == null) {+            false+        } else {+            resolver.openInputStream(file.uri)?.use { input ->+                resolver.openOutputStream(target)?.use { output -> input.copyTo(output) }+            } != null+        }+    } catch (e: Exception) {+        Log.w(TAG, "saveReceivedFile failed for ${file.name}", e)+        false+    }+     // --- Send: discovery + outgoing URIs --------------------------------      private val _isScanning = MutableStateFlow(false)@@ -171,7 +273,7 @@ class ShareViewModel(         nsd.clearDiscoveredDevices()         scanNsdJob = viewModelScope.launch {             try {-                // Browse _up._tcp for WiFi-LAN TCP endpoints (host/port + ServiceId).+                // Browse _FC9F5ED42C8A._tcp for WIFI_LAN endpoints (host/port + name).                 nsd.discover().collect { dev ->                     val current = _discoveredDevices.value                     val merged = mergeDevice(current, dev)@@ -183,7 +285,7 @@ class ShareViewModel(         }         scanBleJob = viewModelScope.launch {             try {-                // Scan GATT 0xFCF1 and parse presence advert for the display name.+                // Scan GATT 0xFEF3 for Nearby Connections BleAdvertisements.                 ble.scan().collect { dev ->                     val current = _discoveredDevices.value                     val merged = mergeDevice(current, dev)@@ -199,10 +301,11 @@ class ShareViewModel(         val idx = current.indexOfFirst { it.endpointId == incoming.endpointId }         return if (idx >= 0) {             val existing = current[idx]-            // BLE presence name takes precedence over the raw ServiceId hex from _up._tcp.+            // Both legs now carry the peer's advertised name, but the mDNS record is the+            // one that also supplies host/port, so prefer it and treat BLE as a tiebreak.             val bestName = when {-                incoming.source == DiscoverySource.Ble && incoming.endpointName.isNotBlank() -> incoming.endpointName-                existing.source == DiscoverySource.Ble && existing.endpointName.isNotBlank() -> existing.endpointName+                incoming.source == DiscoverySource.Nsd && incoming.endpointName.isNotBlank() -> incoming.endpointName+                existing.source == DiscoverySource.Nsd && existing.endpointName.isNotBlank() -> existing.endpointName                 else -> incoming.endpointName.ifBlank { existing.endpointName }             }             val merged = existing.copy(@@ -234,15 +337,20 @@ class ShareViewModel(         val host = device.host         val port = device.port         if (host == null || port == null) {-            Log.w(TAG, "cannot connect to ${device.endpointName}: no host/port (requires _up._tcp browse)")+            Log.w(TAG, "cannot connect to ${device.endpointName}: no host/port (needs the mDNS browse)")             return         }         viewModelScope.launch {             try {+                // A rename while hidden never re-advertised, so refresh the identity the+                // CONNECTION_REQUEST will carry before dialling.+                endpointInfo()?.let {+                    transport.setLocalIdentity(localName.value, it, localEndpointId)+                }                 val conn = transport.connect(host, port)                 _activeConnection.value = conn                 ShareTransferService.startSendMode(appContext, host, port)-                val uris = _outgoingUris.value+                val uris = _outgoingUris.value.ifEmpty { devTestFileUri()?.let(::listOf).orEmpty() }                 if (uris.isNotEmpty()) {                     sendUrisOver(conn, uris)                 }@@ -252,6 +360,26 @@ class ShareViewModel(         }     } +    /**+     * A throwaway file to send when nothing is selected, so a transfer can be exercised+     * without going through the file picker. Dev builds only.+     */+    private fun devTestFileUri(): Uri? {+        if (!BuildConfig.DEV_BUILD) return null+        return try {+            // Not under cache/share_send: that is where uriToTempFile copies *into*, and+            // copying a file onto itself deletes it.+            val f = File(appContext.cacheDir, "dev_test/share-test.txt")+            f.parentFile?.mkdirs()+            f.writeText(":share test payload ${System.currentTimeMillis()}\n")+            Log.i(TAG, "no files selected — sending ${f.name} (dev build only)")+            Uri.fromFile(f)+        } catch (e: Exception) {+            Log.w(TAG, "could not stage the dev test file", e)+            null+        }+    }+     override fun setOutgoingUris(uris: List<Uri>) {         _outgoingUris.value = uris         viewModelScope.launch(Dispatchers.IO) {
share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.ktindex 4cca1f9a67..942a91193e 100644--- a/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/BleDiscoveryManager.kt@@ -7,6 +7,9 @@ import android.bluetooth.BluetoothManager import android.bluetooth.le.AdvertiseCallback import android.bluetooth.le.AdvertiseData import android.bluetooth.le.AdvertiseSettings+import android.bluetooth.le.AdvertisingSet+import android.bluetooth.le.AdvertisingSetCallback+import android.bluetooth.le.AdvertisingSetParameters import android.bluetooth.le.BluetoothLeAdvertiser import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanFilter@@ -17,6 +20,7 @@ import android.content.pm.PackageManager import android.os.ParcelUuid import android.util.Log import androidx.core.content.ContextCompat+import com.vayunmathur.share.protocol.ShareNative import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow@@ -26,26 +30,50 @@ import kotlinx.coroutines.flow.callbackFlow  private const val TAG = "BleDiscovery" -/** GATT service UUID 0xFCF1 (Nearby Presence). 128-bit expansion of 16-bit 0xFCF1. */-const val NEARBY_PRESENCE_SERVICE_UUID_STR = "0000fcf1-0000-1000-8000-00805f9b34fb"-val NEARBY_PRESENCE_SERVICE_UUID: ParcelUuid =-    ParcelUuid.fromString(NEARBY_PRESENCE_SERVICE_UUID_STR)+/**+ * Nearby Connections BLE service UUID — `p000\dses.java:21`.+ *+ * The secondary UUID is `0000FC73-…` (`p000\dses.java:22`) and the GATT-server variant is+ * `0000FEF3-0004-1000-8000-001A11000100` (`:20`). Usage: `p000\dsbl.java:167`, `:455-480`,+ * `:871-876`.+ */+val NEARBY_CONNECTIONS_SERVICE_UUID: ParcelUuid =+    ParcelUuid.fromString("0000FEF3-0000-1000-8000-00805F9B34FB")++/**+ * FastInitiation service UUID — `p000\dvyf.java:10` (`dmxe.m61842a("FE2C")`).+ *+ * Advertised at `p000\dvys.java:288-295`. This is the "a device nearby is sharing"+ * beacon that triggers the receiver's heads-up notification; it is not required for a+ * transfer.+ */+val FAST_INITIATION_SERVICE_UUID: ParcelUuid =+    ParcelUuid.fromString("0000FE2C-0000-1000-8000-00805F9B34FB")  /**- * BLE advertisement + scanning for Nearby Presence (BetoCore public-identity / Everyone mode).+ * BLE advertisement and scanning for the Nearby Connections bootstrap.+ *+ * Advertises a Nearby Connections `BleAdvertisement` as service-data under+ * [NEARBY_CONNECTIONS_SERVICE_UUID], carrying the Nearby Sharing endpoint-info blob a peer+ * needs to list us; a peer that cannot parse it logs `"Failed to parse endpoint %s (%s)"`+ * (`p000\eafg.java:89-93`) and never shows us. Both byte codecs live in Rust+ * (`share/src/main/rust/src/ble_adv.rs`, `endpoint_info.rs`) and are reached through+ * [ShareNative], so there is exactly one implementation of each wire format and it is+ * unit-tested on the host. There is deliberately **no Kotlin fallback**: a silent fallback+ * that emits a *different* wire format is how the previous divergence went unnoticed. If+ * the native library is unavailable, advertising and scanning fail loudly.+ *+ * ## Extended versus legacy advertising  *- * Modern stack (BetoCore):- *  - Advertise: put the Nearby Presence advert BYTES built by the Rust np_adv JNI- *    (UnencryptedEncoder, V0, DeviceInfo DE) as GATT service-data under UUID 0xFCF1.- *    Until the Rust JNI is present, a Kotlin fallback builds the same minimal V0- *    unencrypted advert so the module stays buildable and testable.- *  - Scan: filter for 0xFCF1, extract service-data bytes, and pass them to the Rust- *    parser (JSON byte[] per rustdev's contract) or the String alias / Kotlin fallback- *    to derive the human-readable device name. Identity comes from the BLE presence- *    advert only — no plaintext endpoint_info.+ * A real endpoint info does not fit a legacy 31-byte advertisement: for a 7-character name+ * the extended service-data is 33 bytes and the fast-mode service-data 27, and both exceed+ * the budget once the AD wrappers are added. GMS uses BLE extended advertising here+ * (`p000\dsbl.java:513`, `"Started BLE extended advertising"`) with a legacy fallback+ * (`:624`), so [startAdvertising] prefers `startAdvertisingSet` and falls back to a+ * fast-mode legacy advertisement, which only fits a name of about four characters.  *- * Legacy FC128E01 / 0xFE2C (Google Nearby service-data beacon) has been removed per- * the migration spec. No fallback advertises under the legacy UUID.+ * Nearby Presence (`0xFCF1`, `np_adv`) is a separate subsystem and is not on this path;+ * its Rust entry points remain but are unused by discovery.  */ class BleDiscoveryManager(private val context: Context) { @@ -55,6 +83,8 @@ class BleDiscoveryManager(private val context: Context) {      private var advertiser: BluetoothLeAdvertiser? = null     private var advertiseCallback: AdvertiseCallback? = null+    private var advertisingSetCallback: AdvertisingSetCallback? = null+    private var fastInitAdvertiseCallback: AdvertiseCallback? = null     private var scanCallback: ScanCallback? = null      private val _bleDevices = MutableStateFlow<Map<String, NearbyDevice>>(emptyMap())@@ -63,191 +93,278 @@ class BleDiscoveryManager(private val context: Context) {     private fun hasPermission(permission: String): Boolean =         ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED +    private fun advertiserOrNull(): BluetoothLeAdvertiser? {+        if (!hasPermission(Manifest.permission.BLUETOOTH_ADVERTISE)) {+            Log.w(TAG, "missing BLUETOOTH_ADVERTISE")+            return null+        }+        val btAdapter = adapter ?: run {+            Log.w(TAG, "no BluetoothAdapter")+            return null+        }+        if (!btAdapter.isEnabled) {+            Log.w(TAG, "Bluetooth disabled")+            return null+        }+        return btAdapter.bluetoothLeAdvertiser ?: run {+            Log.w(TAG, "bluetoothLeAdvertiser null")+            null+        }+    }++    private fun lowLatencySettings(connectable: Boolean) = AdvertiseSettings.Builder()+        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)+        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)+        .setConnectable(connectable)+        .build()+     // -------------------------------------------------------------------    // Presence advert bytes — Rust JNI preferred, Kotlin fallback+    // Advertising (Receive: "visible to nearby devices")     // ------------------------------------------------------------------ -    private fun buildPresenceAdvertBytes(deviceName: String): ByteArray {-        try {-            val viaRust = tryBuildPresenceViaRust(device

Diff truncated.