Modern Apps git

← Modern-Apps.git

share: add AirDrop transport probe, fix missing manifest permissions

Commit
12037e1ffa61d1ab061493f73d9902d1822eb662
Author
vayun-mathur <[email protected]>
When
2026-08-22 23:33 UTC (3 months ago)
Parents
4388bea

Diff

share/AIRDROP_FINDINGS.md
diff --git a/share/AIRDROP_FINDINGS.md b/share/AIRDROP_FINDINGS.mdnew file mode 100644index 0000000000..a0d6fa3c9a--- /dev/null+++ b/share/AIRDROP_FINDINGS.md@@ -0,0 +1,326 @@+# AirDrop transport findings++Ground truth for what an AirDropping iPhone is actually reachable on **from an ordinary+third-party Android app**. Same role as `QUICK_SHARE_VERIFICATION.md`: claims here should be+backed by an observation, and anything unverified says so.++## The question++Quick Share on the Pixel 10 interoperates with AirDrop. If AirDrop's peer-to-peer link is a+standard one (Wi-Fi Direct or Wi-Fi Aware), an ordinary app can reach it — Android exposes+`WifiP2pManager` and `WifiAwareManager` publicly, and a `_airdrop._tcp` DNS-SD registration plus+an HTTPS server implementing `/Discover`, `/Ask` and `/Upload` would be a normal amount of work.+If it is AWDL, no app can reach it: there is no Android API for AWDL, and the open-source+equivalent needs 802.11 monitor mode and frame injection that the Wi-Fi HAL does not expose.++So the transport determines whether a receive path is buildable at all. It is worth measuring+rather than arguing about.++## Prior expectation (superseded by the APK analysis below)++Going in, the expectation was **AWDL**, on three grounds:++1. Whatever Google shipped had to interoperate with *unmodified* iPhones, so the transport must+   be something iOS already speaks. Google cannot change Apple's side.+2. Meta's internal Wi-Fi Aware working-group FAQ (June 2025) still describes AirDrop as+   AWDL-based: *"Historically, Apple has not adopted Wi-Fi Aware, instead relying on its+   proprietary solution, AWDL (Apple Wireless Direct Link), for applications like AirDrop."*+   Apple's DMA-driven iOS 26 change exposes **Wi-Fi Aware** (NAN) to third-party apps, which is+   a distinct technology from Wi-Fi Direct and is a *new third-party capability*, not a change+   to AirDrop's own transport.+3. Google's security blog restricts the feature to AirDrop's **"Everyone for 10 minutes"** mode.+   Contacts-only AirDrop validates identity with Apple-issued client certificates that Google+   cannot mint; "Everyone" accepts self-signed. That is the fingerprint of implementing the real+   AirDrop protocol rather than substituting a transport.++The widely-repeated explanation for *how* Google managed it — that the Pixel 10's Broadcom Wi-Fi+silicon has AWDL-capable firmware — is **not verified here** and should not be repeated as fact.++**Update:** the `com.google.android.mosey` APK analysis below resolves this. The transport is a+bespoke channel-hopping link on a `mosey0` interface, created by a Pixel-only privileged daemon —+not Wi-Fi Direct, and not Wi-Fi Aware. Read that section rather than reasoning from the three+points above.++## Running the probe++1. Build and install: `./gradlew :share:installDev`.+2. Grant the permissions the app asks for on launch. `BLUETOOTH_SCAN` and `NEARBY_WIFI_DEVICES`+   are the two the probe cannot run without.+3. Put both devices on the same Wi-Fi network. That is not how AirDrop works, but it is what+   makes the mDNS leg meaningful — an `_airdrop._tcp` record on the infrastructure network would+   settle the question immediately, so it is worth ruling out.+4. On the iPhone: Settings → General → AirDrop → **Everyone for 10 minutes**.+5. On the iPhone: share any file and leave the AirDrop picker open on screen. It stops beaconing+   when the sheet closes, and a negative result recorded after it closed is worthless.+6. In `:share`, open **AirDrop probe** from the top bar and press **Start probe**.++Logcat, if reading it off-device:++```+adb logcat -s AppleBeacon:V WifiDirectProbe:V AirDropProbe:V+```++### Reading the result++The BLE leg is the control. `AppleBeacon` logging `AIRDROP beacon from …` is proof the iPhone is+soliciting a transfer *at that moment*; without that line in the same window, nothing the other+two legs report means anything.++Three outcomes worth distinguishing:++| BLE `0x05` beacon | Wi-Fi Direct peer | `_airdrop._tcp` on wlan0 | Reading |+|---|---|---|---|+| yes | yes | either | AirDrop is reachable over Wi-Fi Direct — a receive path is buildable, and the prior expectation above is wrong |+| yes | no | yes | AirDrop is reachable over infrastructure mDNS — buildable |+| yes | no | no | Not reachable from this app on this device; consistent with AWDL |+| no | — | — | No result. The sheet was not open, or Bluetooth is off. Re-run |++`P2pObservations.unavailableReason` is reported separately from an empty peer list on purpose: a+probe that could not run and a probe that ran and saw nothing produce the same silence otherwise,+and only one of them is evidence.++Two limits to be honest about:++- **The BLE and Wi-Fi Direct sightings cannot be correlated by address.** Apple rotates a+  resolvable private address on BLE, and Wi-Fi Direct reports a different interface MAC. Any+  match between the two legs is temporal — "both were seen in the same window" — not+  identity-based. `candidateP2pPeers` therefore returns every peer rather than pretending to+  filter.+- A negative result is scoped to **this handset and this API surface**. It does not establish+  what Apple does internally, only what an app can reach here — which is the question that+  decides whether anything ships.++## Observations++### 2026-08-22 — Pixel 9 Pro XL (komodo), Android 17 / API 37++**Result: AirDrop was not reachable over Wi-Fi Direct or infrastructure mDNS while actively+beaconing. Consistent with AWDL.**++Probe run at 16:17:42–16:18:12 local, iPhone ~1 m away with the AirDrop picker open and AirDrop+set to Everyone. iOS version not recorded.++BLE control — the iPhone *was* soliciting a transfer throughout:++```+AIRDROP beacon 11:C0:39:D2:6A:D9 rssi=-46+  AirDrop(0x05)[18B]=000000000000000001ebd71809850e6f1500+  v1 contactHashes=[appleId=ebd7, phone=1809, 850e, 6f15]+```++Wi-Fi Direct — four discovery cycles over 30 s, **no Apple device among the peers**:++```+16:17:45  "DIRECT-98-HP Tango"        b2:0c:d1:0a:b8:98  AVAILABLE  primaryType=3-0050F204-1 (printer)+16:17:45  "Roku Ultra"                ca:3a:6b:1f:51:1a  AVAILABLE  primaryType=7-0050F204-1 (display)+16:17:45  "55\" Mini LED"              82:0d:3f:85:91:18  AVAILABLE  primaryType=7-0050F204-1 (display)+16:17:59  "[TV] Samsung 7 Series (65)" 56:3a:d6:4e:34:f2  AVAILABLE  primaryType=7-0050F204-1 (display)+DNS-SD over P2P: no services published by any peer+```++mDNS on `wlan0` — **no `_airdrop._tcp`, but the iPhone was plainly there**:++```+_companion-link._tcp  "vayun-mac"       -> 192.168.0.127:63038  attrs=[rpAD rpBA rpFl rpHA rpHI rpHN rpVr rpMac]+_rdlink._tcp          "Vayun's iPhone"  -> 192.168.0.209:49179  attrs=[rpAD rpBA rpVr]+_airdrop._tcp         (none)+```++### Why this is a real negative and not a broken probe++Every leg proved itself working in the same window, which is what makes the two absences+meaningful:++- mDNS resolved **the AirDropping iPhone itself** at `192.168.0.209` under `_rdlink._tcp`. So the+  browse worked, the phone was on the same LAN, and it *was* publishing Apple services there —+  just not `_airdrop._tcp`. The absence is specific to AirDrop, not a mDNS failure.+- Wi-Fi Direct discovery returned four peers including a printer and three displays, so P2P+  discovery was functioning; the iPhone simply was not advertising on it.+- The BLE beacon was present at −46 dBm throughout, so the sheet was genuinely open.++AirDrop's discovery is therefore on a link this device cannot see. That is what AWDL predicts.++### Caveats++- This is a **Pixel 9 Pro XL, not a Pixel 10**, so it has none of Google's AirDrop interop. That+  limits what the run can say about *how Google did it* — but not about the Wi-Fi Direct+  hypothesis, because Wi-Fi Direct is fully supported on this handset and the iPhone still did+  not appear on it.+- **Wi-Fi Aware (NAN) was not probed.** It is the other standards-based candidate and the one+  iOS 26 exposes to third-party apps. Untested here.+- The two captures disagree on the order of the last two hash slots — `…6f15850e00` on the first+  run, `…850e6f1500` on the second, same four values. So the `email` / `email2` labels in+  `AirDropBeacon` are **not** a stable field mapping; treat those two slots as an unordered pair.+  The 18-byte length, the eight leading zeros, the version byte at offset 8 and the trailing zero+  are all confirmed.++### Bugs this run surfaced (both fixed)++1. **mDNS never ran on the first attempt.** All four browses failed instantly with+   `FAILURE_INTERNAL_ERROR` (0). Cause: `NsdManager.discoverServices` binds to the *default*+   network, which was cellular (`rmnet16`) even though Wi-Fi was associated as `mathurs-5` at+   192.168.0.76. Fixed by passing a `NetworkRequest` for `TRANSPORT_WIFI`. **The same latent bug+   exists in `NsdDiscoveryManager`**, which uses the plain three-argument call — meaning Quick+   Share discovery and advertising also silently fail whenever cellular is the default network.+   That is worth fixing separately; `WIFI_LAN` is the only medium `:share` can accept a transfer+   on.+2. **`discoverPeers()` was called once.** A single call covers one scan cycle and then lapses, so+   a short window could have produced a false negative. Now re-issued every 10 s — which is how+   the fourth peer at 16:17:59 was caught at all.++## APK analysis: `com.google.android.mosey` ("Quick Share extension")++Static analysis of `com.google.android.mosey` 1.0.962636193 (versionCode 39073, `min_api 36`,+arm64-v8a), the package that implements Quick Share ↔ AirDrop interop. Strings extracted from+`classes*.dex` and the binary `AndroidManifest.xml` string pool. **This supersedes guesswork+about the transport.**++### It is not Wi-Fi Direct and not Wi-Fi Aware++Searched for the whole Wi-Fi Direct and Wi-Fi Aware discovery surface. **Not one of these+appears anywhere in the DEX:**++```+discoverPeers   discoverServices   WifiP2pConfig   createGroup   addLocalService+PublishConfig   SubscribeConfig    PeerHandle      WifiAwareNetworkSpecifier+WifiAwareSession  PublishDiscoverySession  SubscribeDiscoverySession+```++What *is* referenced from those packages is only `WifiP2pManager$Channel`, `WifiP2pGroup`,+`GroupInfoListener`, `requestGroupInfo`, `removeGroup`, and a bare `WifiAwareManager` class+reference, all inside one class `com.google.android.mosey.network.WifiP2pAware`. Querying group+info and *removing* groups, with no config, no `createGroup` and no `connect`, is coexistence+management — P2P, NAN and this feature all contend for the same radio, so it tears down or avoids+conflicting sessions. It is not how a peer is discovered.++So AirDrop is not discovered over Wi-Fi Direct. That matches the 2026-08-22 device run exactly:+the beaconing iPhone never appeared among four Wi-Fi Direct peers.++### What it actually does: a bespoke `mosey0` link, registered as a network++```+mosey0+Network interface 'mosey0' not found.+Failed to get network interface 'mosey0'+MoseyController got interface %s+===== MoseyController start: channels: %s+Channel hopping is supported, notify daemon with necessary events+notifyDaemonOfStaChannelUpdate: %s+notifyDaemonOfStartTransfer: %s   notifyDaemonOfEndTransfer: %s+com/google/android/mosey/network/MoseyNetworkAgent      android/net/NetworkAgent+com/google/android/mosey/network/MoseyNetworkProvider   android/net/NetworkProvider+com/google/android/mosey/network/StaNetwork+```++Google created **its own L2 link on a virtual interface `mosey0`**, driven by a native **daemon**+it notifies of channel-hopping events, of the current **STA channel**, and of transfer start/end.+It then registers `mosey0` with ConnectivityManager via `NetworkAgent` / `NetworkProvider` so+ordinary IP sockets work over it. Regulatory-domain code is extensive (`countryCode` from+telephony, WifiManager and location) because it picks the channels it hops on.++A channel-hopping link whose availability windows are aligned to the infrastructure STA channel,+addressed over IPv6 link-local:++```+Link-local IPv6 found on %s+Failed to bind attemptSocket to local IPv6 address: %s+Explicitly bound attemptSocket to local IPv6 link-local address: %s+```++is a functional description of **AWDL**. The literal string `awdl` does not appear in this APK —+but it would not: the link implementation is not here. It lives behind++```+com.google.pixel.moseyservice.IMoseyService+com.google.android.moseyservice.IMoseyService+Lcom/google/android/moseylib/MoseyManager;+Error linking against Mosey Lib.   Got null mosey binder.+binder is null, unable to update country code or stop mosey.+```++a **Pixel-specific privileged system service** plus a `uses-library` shared library+`com.google.android.moseylib`, neither of which ships in this APK.++### On top of the link: stock AirDrop application layer++```+_airdrop._tcp                                  AirDrop/1.0+com/google/android/mosey/compat/NsdManagerCompat   android/net/nsd/DiscoveryRequest$Builder+NsdManagerCompat acquired multicast lock %d+/Discover   /Ask   /Upload+Pinging /Discover for target %s     Socket timed out sending ASK request+bplist   <plist version="1.0">   <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ...>+Failed to parse discover response plist+SenderID   ReceiverComputerName+application/x-cpio+okhttp/4.12.0 + javax.net.ssl.SSLContext / X509Certificate / SSLSockets+```++Plain DNS-SD `_airdrop._tcp` over `NsdManager` (network-bound via API 36's `DiscoveryRequest`,+with a multicast lock), then HTTPS with `/Discover`, `/Ask`, `/Upload`, Apple binary plists, and+a cpio archive body. BLE scan and advertise are present via `BluetoothLeScannerCompat` /+`BluetoothLeAdvertiserCompat` with `setManufacturerData` for the beacon bootstrap.++This is why the device run saw no `_airdrop._tcp` on `wlan0` while resolving the same iPhone+under `_rdlink._tcp`: AirDrop's DNS-SD record is published on the peer-to-peer link, not on the+infrastructure network. Mosey reaches it by *being on that link*.++### Why `:share` cannot do this++The permissions that bring up the link are all `signature|privileged`:++```+android.permission.MANAGE_WIFI_INTERFACES              android.permission.NETWORK_FACTORY+android.permission.CREATE_APP_SPECIFIC_NETWORK         android.permission.LOCATION_HARDWARE+android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS+android.permission.MANAGE_WIFI_NETWORK_SELECTION       android.permission.BLUETOOTH_PRIVILEGED+```++A third-party app signed with its own key cannot hold any of them. On top of that it would need+to bind `com.google.pixel.moseyservice.IMoseyService` and link `com.google.android.moseylib`.+Neither the package nor the library is present on the Pixel 9 Pro XL used here+(`pm list packages`/`cmd package list libraries` both return nothing for `mosey`) — it is+Pixel 10 only.++**Conclusion: AirDrop receive is not implementable in `:share`.** Not for want of protocol+knowledge — the application layer above is entirely reproducible — but because the link it runs+on can only be created by privileged, Pixel-specific platform code. This is a hard platform+boundary, not a gap in effort.++### What remains unproven++Whether `mosey0` is AWDL on the wire, or an AWDL-compatible variant, cannot be settled from this+APK; the frame format is in the daemon and `moseylib`. The evidence here establishes the *shape*+(channel-hopping, STA-aligned, IPv6 link-local, bespoke interface) and, decisively for this+repo, the *reachability* — which is the only part that affects what can ship.++## What is decoded so far++`AppleBeaconScanner` decodes Apple's manufacturer-specific data (company ID `0x004C`) as a bare+sequence of `type, length, value` records, and AirDrop's `0x05` record — always 18 bytes — as:++| Offset | Size | Field |+|---|---|---|+| 0 | 8 | zeros |+| 8 | 1 | version |+| 9 | 2 | Apple ID hash prefix |+| 11 | 2 | phone number hash prefix |+| 13 | 2 | email hash prefix |+| 15 | 2 | second email hash prefix |+| 17 | 1 | zero terminator |++The four prefixes are the leading two bytes of `SHA-256` over the sender's contact identifiers,+which a contacts-only receiver matches against its own address book. Two bytes identify nobody+on their own; they are decoded only so sightings can be correlated across adverts. The 18-byte+length, the eight leading zeros, the version byte and the trailing zero are **confirmed** against+the 2026-08-22 capture; the split of the last two slots into `email` and `email2` is **not** —+see the caveat in that run's notes.++## If the transport turns out to be reachable++**It is not** — see the APK analysis. Kept only to record what the shape would have been: the+seam is `ShareReceiveController`, which hard-wires exactly one `NsdDiscoveryManager` and one+`TcpTransport`; an AirDrop path would be a sibling of each, and `NearbyDevice` would need a+transport discriminator beyond `DiscoverySource`. The application layer is the larger half and is+fully reproducible: DNS-SD registration, TLS, Apple binary plists for `/Discover` and `/Ask`, and+a gzipped cpio body on `/Upload`. Only the link is out of reach.
share/src/main/AndroidManifest.xml
diff --git a/share/src/main/AndroidManifest.xml b/share/src/main/AndroidManifest.xmlindex 33052fc548..07313a361f 100644--- a/share/src/main/AndroidManifest.xml+++ b/share/src/main/AndroidManifest.xml@@ -1,9 +1,48 @@ <?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">++    <!--+      Every permission the discovery and transfer paths actually exercise. These were missing+      entirely, which made advertising, scanning, mDNS, the foreground service, notifications+      and the boot receiver all fail silently at runtime.++      neverForLocation on both radio scans is what keeps this list free of+      ACCESS_FINE_LOCATION: minSdk is 31, so the pre-Android-12 location-backed scan fallback+      is unreachable and nothing here needs to derive position.+    -->+    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />+    <uses-permission+        android:name="android.permission.BLUETOOTH_SCAN"+        android:usesPermissionFlags="neverForLocation" />+    <uses-permission+        android:name="android.permission.NEARBY_WIFI_DEVICES"+        android:usesPermissionFlags="neverForLocation" />++    <!--+      Local Network Protections (Android 16+). Gates mDNS and every LAN socket; without it+      NsdManager.registerService throws and the device is invisible over WIFI_LAN, which is+      the only medium a transfer is accepted on.+    -->+    <uses-permission+        android:name="android.permission.ACCESS_LOCAL_NETWORK"+        tools:targetApi="36" />++    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+    <!-- Wi-Fi P2P service discovery drives the radio, so it needs the write-side too. -->+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />      <uses-feature android:name="android.hardware.bluetooth" android:required="false" />     <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />     <uses-feature android:name="android.hardware.wifi" android:required="false" />+    <uses-feature android:name="android.hardware.wifi.direct" android:required="false" />      <application         android:allowBackup="true"
share/src/main/java/com/vayunmathur/share/Navigation.kt
diff --git a/share/src/main/java/com/vayunmathur/share/Navigation.kt b/share/src/main/java/com/vayunmathur/share/Navigation.ktindex d09e17807a..e2fce621a9 100644--- a/share/src/main/java/com/vayunmathur/share/Navigation.kt+++ b/share/src/main/java/com/vayunmathur/share/Navigation.kt@@ -1,39 +1,21 @@ package com.vayunmathur.share -import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.share.platform.ShareViewModel-import com.vayunmathur.share.ui.ShareSendScreen+import com.vayunmathur.share.ui.AirDropProbePage+import com.vayunmathur.share.ui.ShareSendPage  @Composable fun Navigation(viewModel: ShareViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Share)     MainNavigation(backStack) {         entry<Route.Share> {-            ShareApp(viewModel)+            ShareSendPage(viewModel, onOpenAirDropProbe = { backStack.add(Route.AirDropProbe) })+        }+        entry<Route.AirDropProbe> {+            AirDropProbePage(backStack)         }-    }-}--/**- * The whole in-app surface: sending.- *- * Receiving has no screen. It is driven by notifications and turned on and off from a Quick- * Settings tile, so it works when the app has never been opened.- */-@Composable-private fun ShareApp(viewModel: ShareViewModel) {-    AppScaffold(title = stringResource(R.string.app_name), scrollBehavior = appBarScrollBehavior()) { padding ->-        ShareSendScreen(-            viewModel = viewModel,-            modifier = Modifier.fillMaxSize().padding(padding),-        )     } }
share/src/main/java/com/vayunmathur/share/Route.kt
diff --git a/share/src/main/java/com/vayunmathur/share/Route.kt b/share/src/main/java/com/vayunmathur/share/Route.ktindex 577747ba11..b60d82c2c5 100644--- a/share/src/main/java/com/vayunmathur/share/Route.kt+++ b/share/src/main/java/com/vayunmathur/share/Route.kt@@ -7,4 +7,8 @@ import kotlinx.serialization.Serializable sealed interface Route : NavKey {     @Serializable     data object Share : Route++    /** Diagnostic: which transports an AirDropping iPhone is reachable on. Not a user feature. */+    @Serializable+    data object AirDropProbe : Route }\ No newline at end of file
share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AirDropProbe.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AirDropProbe.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AirDropProbe.ktnew file mode 100644index 0000000000..a9f2d68343--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AirDropProbe.kt@@ -0,0 +1,365 @@+package com.vayunmathur.share.platform.discovery.apple++import android.content.Context+import android.net.NetworkCapabilities+import android.net.NetworkRequest+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import android.os.Build+import android.util.Log+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.flow.channelFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.launch++private const val TAG = "AirDropProbe"++/**+ * AirDrop's DNS-SD service type.+ *+ * Apple publishes this on the peer-to-peer link, not on the infrastructure network. It is+ * browsed here anyway, on `wlan0`, precisely to test that claim: if a record ever shows up,+ * AirDrop is reachable without a proprietary link layer and this whole question is settled the+ * easy way.+ */+private const val AIRDROP_SERVICE_TYPE = "_airdrop._tcp"++/**+ * Other Apple service types worth browsing, as corroboration.+ *+ * `_companion-link._tcp` and `_rdlink._tcp` back Continuity and Sidecar. If those resolve on+ * the LAN while `_airdrop._tcp` never does, that is evidence the silence is specific to+ * AirDrop's link layer rather than a general mDNS failure on this device — which is the+ * difference between a finding and a broken probe.+ */+private val APPLE_SERVICE_TYPES = listOf(+    AIRDROP_SERVICE_TYPE,+    "_companion-link._tcp",+    "_rdlink._tcp",+    "_apple-mobdev2._tcp",+)++/** One mDNS record seen on the infrastructure network. */+data class MdnsSighting(+    val serviceType: String,+    val serviceName: String,+    val host: String?,+    val port: Int?,+    val resolved: Boolean,+)++/**+ * Browse arbitrary DNS-SD service types on the normal Wi-Fi interface.+ *+ * Separate from [com.vayunmathur.share.platform.discovery.NsdDiscoveryManager], which is+ * hard-wired to the Quick Share type and applies Quick Share's record validation. This one+ * validates nothing and reports whatever it sees, because for a probe an unparseable record is+ * still a result.+ */+class MdnsBrowser(private val context: Context) {++    private val nsdManager: NsdManager? =+        context.getSystemService(Context.NSD_SERVICE) as? NsdManager++    private val _found = MutableStateFlow<Map<String, MdnsSighting>>(emptyMap())+    val found: StateFlow<Map<String, MdnsSighting>> = _found.asStateFlow()++    /**+     * Forget every record seen so far.+     *+     * Called once per probe run rather than per [browse] call, because all the service types+     * share one map and a per-browse reset would wipe its siblings.+     */+    fun reset() {+        _found.value = emptyMap()+    }++    fun browse(serviceType: String): Flow<MdnsSighting> = callbackFlow {+        val mgr = nsdManager ?: run {+            Log.w(TAG, "NsdManager unavailable")+            close()+            return@callbackFlow+        }+        val listener = object : NsdManager.DiscoveryListener {+            override fun onDiscoveryStarted(regType: String) {+                Log.d(TAG, "mDNS browse started: $regType")+            }++            override fun onServiceFound(service: NsdServiceInfo) {+                val name = service.serviceName ?: return+                val key = "$serviceType|$name"+                val unresolved = MdnsSighting(serviceType, name, null, null, resolved = false)+                _found.value = _found.value + (key to unresolved)+                Log.i(TAG, "mDNS FOUND $serviceType instance=\"$name\"")+                trySend(unresolved)+                try {+                    mgr.resolveService(service, object : NsdManager.ResolveListener {+                        override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {+                            Log.w(TAG, "mDNS resolve failed for $name: $errorCode")+                        }++                        override fun onServiceResolved(info: NsdServiceInfo) {+                            val sighting = MdnsSighting(+                                serviceType = serviceType,+                                serviceName = info.serviceName ?: name,+                                host = info.host?.hostAddress,+                                port = info.port.takeIf { it > 0 },+                                resolved = true,+                            )+                            _found.value = _found.value + (key to sighting)+                            Log.i(+                                TAG,+                                "mDNS RESOLVED $serviceType \"$name\" -> " ++                                    "${sighting.host}:${sighting.port} attrs=${info.attributes.keys}",+                            )+                            trySend(sighting)+                        }+                    })+                } catch (e: Exception) {+                    Log.w(TAG, "resolveService threw for $name", e)+                }+            }++            override fun onServiceLost(service: NsdServiceInfo) {+                val name = service.serviceName ?: return+                _found.value = _found.value - "$serviceType|$name"+                Log.d(TAG, "mDNS lost $serviceType \"$name\"")+            }++            override fun onDiscoveryStopped(type: String) {+                Log.d(TAG, "mDNS browse stopped: $type")+            }++            override fun onStartDiscoveryFailed(type: String, errorCode: Int) {+                Log.w(TAG, "mDNS startDiscovery failed $type: $errorCode")+                close()+            }++            override fun onStopDiscoveryFailed(type: String, errorCode: Int) {+                Log.w(TAG, "mDNS stopDiscovery failed $type: $errorCode")+            }+        }+        try {+            startDiscovery(mgr, serviceType, listener)+        } catch (e: SecurityException) {+            // Android 16+ Local Network Protections. Distinguish this in the log: a blocked+            // browse produces the same empty result as a browse that found nothing.+            Log.e(TAG, "mDNS browse of $serviceType blocked — ACCESS_LOCAL_NETWORK not granted", e)+            close(e)+            return@callbackFlow+        } catch (e: Exception) {+            Log.w(TAG, "discoverServices($serviceType) threw", e)+            close(e)+            return@callbackFlow+        }+        awaitClose {+            try {+                mgr.stopServiceDiscovery(listener)+            } catch (_: Exception) {+            }+        }+    }++    /**+     * Start discovery **bound to the Wi-Fi network**, not to the default one.+     *+     * The three-argument [NsdManager.discoverServices] uses the process's default network. On a+     * phone with a SIM the default network is usually cellular even while Wi-Fi is associated,+     * and mDNS on a cellular interface fails immediately with `FAILURE_INTERNAL_ERROR` (0) — no+     * exception, just a callback. That is exactly the failure this probe hit on first run: the+     * device was on `mathurs-5` at 192.168.0.76 while routing through `rmnet16`, so all four+     * browses died before reaching the LAN and the "no `_airdrop._tcp`" result was meaningless.+     *+     * Passing a [NetworkRequest] for [NetworkCapabilities.TRANSPORT_WIFI] makes the platform run+     * the browse on the Wi-Fi network regardless of which one is default. The overload needs+     * API 33; below that the default-network call is the only option.+     */+    private fun startDiscovery(+        mgr: NsdManager,+        serviceType: String,+        listener: NsdManager.DiscoveryListener,+    ) {+        if (Build.VERSION.SDK_INT >= 33) {+            val wifiOnly = NetworkRequest.Builder()+                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)+                .build()+            mgr.discoverServices(+                serviceType,+                NsdManager.PROTOCOL_DNS_SD,+                wifiOnly,+                // The context's main executor rather than a new single-thread one: this is called+                // once per service type, and an executor created here would leak a thread per+                // browse with nothing owning its shutdown. The callbacks only log and update a+                // StateFlow.+                context.mainExecutor,+                listener,+            )+        } else {+            mgr.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, listener)+        }+    }+}++/**+ * What every observable transport saw at one instant.+ *+ * [airDropBeacons] is the subset of [appleBeacons] carrying AirDrop's `0x05` record, i.e. the+ * Apple devices that currently have a share sheet open.+ */+data class AirDropProbeReport(+    val appleBeacons: List<AppleBeaconSighting> = emptyList(),+    val p2p: P2pObservations = P2pObservations(),+    val mdns: List<MdnsSighting> = emptyList(),+) {+    val airDropBeacons: List<AppleBeaconSighting> get() = appleBeacons.filter { it.isAirDropping }++    val sawAirDropBeacon: Boolean get() = airDropBeacons.isNotEmpty()++    val sawAirDropOverMdns: Boolean+        get() = mdns.any { it.serviceType.startsWith(AIRDROP_SERVICE_TYPE) }++    /**+     * Peers that are plausibly the beaconing iPhone.+     *+     * Deliberately every peer, not a filtered subset. A BLE advert uses a rotating resolvable+     * private address and Wi-Fi Direct reports a different interface MAC, so the two sightings+     * of one physical phone **cannot be correlated by address** — only by the fact that they+     * appeared at the same time. Any filter here would be a guess dressed up as a match.+     */+    val candidateP2pPeers: List<P2pPeer> get() = p2p.peers.values.toList()++    /**+     * A plain-language reading of the evidence.+     *+     * Phrased as what was observed rather than as a conclusion about Apple's design, because+     * this probe can only ever show what is reachable *from this Android device*. "Not visible+     * over Wi-Fi Direct" is consistent with a proprietary link layer, but it is also+     * consistent with a driver or permission problem on this handset — hence the explicit+     * unavailability reporting.+     */+    fun summary(): String = buildString {+        if (!sawAirDropBeacon) {+            appendLine("No AirDrop beacon in range. Open the share sheet on the iPhone and keep it open.")+            if (appleBeacons.isNotEmpty()) {+                appendLine("(${appleBeacons.size} Apple device(s) beaconing, none with an AirDrop record.)")+            }+            return@buildString+        }+        appendLine("AirDrop beacon seen from ${airDropBeacons.size} device(s) — a share sheet is open nearby.")+        airDropBeacons.forEach { b ->+            val hashes = b.airDrop?.populatedHashes()?.joinToString(", ").orEmpty()+            appendLine("  BLE ${b.address} rssi=${b.rssi} contactHashes=[$hashes]")+        }+        val reason = p2p.unavailableReason+        when {+            reason != null -> appendLine("Wi-Fi Direct: could not probe — $reason")+            p2p.peers.isEmpty() -> appendLine("Wi-Fi Direct: 0 peers while AirDrop is beaconing.")+            else -> {+                appendLine("Wi-Fi Direct: ${p2p.peers.size} peer(s) visible:")+                candidateP2pPeers.forEach { appendLine("  P2P \"${it.deviceName}\" ${it.deviceAddress} ${it.statusName}") }+            }+        }+        if (p2p.services.isEmpty()) {+            appendLine("Wi-Fi Direct DNS-SD: no services published by any peer.")+        } else {+            appendLine("Wi-Fi Direct DNS-SD: ${p2p.services.size} service record(s):")+            p2p.services.values.forEach {+                appendLine("  ${it.instanceName} ${it.registrationType} from ${it.deviceAddress} txt=${it.txt}")+            }+        }+        appendLine(+            if (sawAirDropOverMdns) {+                "mDNS on wlan0: an _airdrop._tcp record IS visible on the infrastructure network."+            } else {+                "mDNS on wlan0: no _airdrop._tcp record (${mdns.size} other Apple record(s))."+            }+        )+    }+}++/**+ * Runs every transport an Android app can observe, at once, and reports what each one saw.+ *+ * ## Purpose+ *+ * To answer one question with data instead of recollection: **when an iPhone is actively+ * soliciting an AirDrop transfer, is it reachable from an ordinary Android app over any+ * transport the platform exposes?**+ *+ * The three legs are run simultaneously and on purpose:+ *  - [AppleBeaconScanner] proves the iPhone is in AirDrop discovery *at that moment*. Without+ *    it, a negative result elsewhere means nothing — it could just be that the sheet timed out.+ *  - [WifiDirectProbe] tests peer and DNS-SD visibility over Wi-Fi Direct.+ *  - [MdnsBrowser] tests whether `_airdrop._tcp` is reachable on the infrastructure network.+ *+ * ## What a negative result does and does not prove+ *+ * If the beacon is present and both other legs stay empty, AirDrop's discovery and transfer+ * are not reachable from this app, and no amount of Kotlin will make them reachable. That is a+ * statement about *this device and this API surface*, which is exactly the scope that matters+ * for shipping something here. It is **not** a claim about Apple's internals, and the probe is+ * built so that a genuine failure to probe ([P2pObservations.unavailableReason]) is reported+ * distinctly from a successful probe that found nothing.+ *+ * Findings from real runs belong in `share/AIRDROP_FINDINGS.md`, alongside the logcat filter+ * used to capture them.+ */+class AirDropProbe(context: Context) {++    private val beacons = AppleBeaconScanner(context)+    private val wifiDirect = WifiDirectProbe(context)+    private val mdns = MdnsBrowser(context)++    /**+     * Start every leg and emit a fresh report whenever any of them changes.+     *+     * Cancelling the collection tears down the BLE scan, the P2P discovery and every mDNS+     * browse — all three hold radio resources and none of them stop on their own.+     */+    fun run(): Flow<AirDropProbeReport> = channelFlow {+        mdns.reset()+        launch { beacons.scan().collect { } }+        launch { wifiDirect.probe().collect { } }+        APPLE_SERVICE_TYPES.forEach { type ->+            launch { mdns.browse(type).collect { } }+        }+        // Rotating private addresses mean the beacon map would otherwise grow without bound+        // over a long capture, and stale entries would overstate how many phones are present.+        launch {+            while (true) {+                delay(BEACON_EXPIRY_MS)+                beacons.expire(BEACON_EXPIRY_MS)+            }+        }+        launch {+            combine(+                beacons.sightings,+                wifiDirect.observations,+                mdns.found,+            ) { sightings, p2p, records ->+                AirDropProbeReport(+                    appleBeacons = sightings.values.sortedByDescending { it.rssi },+                    p2p = p2p,+                    mdns = records.values.toList(),+                )+            }.collect { send(it) }+        }+    }++    private companion object {+        /**+         * How long a beacon stays in the report after its last sighting.+         *+         * An iPhone re-advertises several times a second while its sheet is open, so anything+         * this stale is gone. Short enough that closing the sheet is visible in the UI within+         * a few seconds.+         */+        const val BEACON_EXPIRY_MS = 10_000L+    }+}
share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScanner.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScanner.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScanner.ktnew file mode 100644index 0000000000..884d371f31--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScanner.kt@@ -0,0 +1,365 @@+package com.vayunmathur.share.platform.discovery.apple++import android.Manifest+import android.annotation.SuppressLint+import android.bluetooth.BluetoothAdapter+import android.bluetooth.BluetoothManager+import android.bluetooth.le.ScanCallback+import android.bluetooth.le.ScanFilter+import android.bluetooth.le.ScanResult+import android.bluetooth.le.ScanSettings+import android.content.Context+import android.content.pm.PackageManager+import android.util.Log+import androidx.core.content.ContextCompat+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow++private const val TAG = "AppleBeacon"++/**+ * Apple's Bluetooth SIG company identifier, as it appears in a BLE+ * `Manufacturer Specific Data` AD structure.+ *+ * On the wire the two ID bytes are little-endian (`4C 00`); Android's+ * [ScanRecord.getManufacturerSpecificData] and [ScanFilter] both take the decoded integer, so+ * this is `0x004C` rather than `0x4C00`.+ */+const val APPLE_COMPANY_ID: Int = 0x004C++/** AirDrop's TLV type inside Apple's manufacturer data. Always carries an 18-byte value. */+const val APPLE_TLV_AIRDROP: Int = 0x05++/**+ * Apple's documented-by-reverse-engineering TLV types, for readable logs.+ *+ * Names follow the published surveys of Apple's continuity/proximity BLE protocols. Only+ * [APPLE_TLV_AIRDROP] is load-bearing here; the rest exist so a capture can be read at a+ * glance and so an unexpected type is obviously unexpected.+ */+private val APPLE_TLV_NAMES: Map<Int, String> = mapOf(+    0x02 to "iBeacon",+    0x05 to "AirDrop",+    0x06 to "HomeKit",+    0x07 to "ProximityPairing",+    0x08 to "HeySiri",+    0x09 to "AirPlayTarget",+    0x0A to "AirPlaySource",+    0x0B to "MagicSwitch",+    0x0C to "Handoff",+    0x0D to "TetheringTargetPresence",+    0x0E to "TetheringSourcePresence",+    0x0F to "NearbyAction",+    0x10 to "NearbyInfo",+    0x12 to "FindMy",+)++/** One type-length-value record from an Apple manufacturer-data blob. */+data class AppleTlv(val type: Int, val value: ByteArray) {+    val name: String get() = APPLE_TLV_NAMES[type] ?: "Unknown"++    override fun toString(): String = "$name(0x%02x)[${value.size}B]=${value.toHex()}".format(type)++    // Identity has to be by content: these are compared to decide whether a beacon changed,+    // and the default array equality would report every rescan as a new observation.+    override fun equals(other: Any?): Boolean =+        this === other || (other is AppleTlv && type == other.type && value.contentEquals(other.value))++    override fun hashCode(): Int = 31 * type + value.contentHashCode()+}++/**+ * AirDrop's `0x05` record, as emitted by a device with the share sheet open.+ *+ * Layout of the 18-byte value, per the published analyses of Apple's AirDrop BLE beacon:+ * eight zero bytes, a version byte, then four two-byte truncated `SHA-256` prefixes of the+ * sender's contact identifiers (Apple ID, phone number, and two email addresses), then a+ * zero terminator. A receiver in contacts-only mode matches those prefixes against its own+ * address book to decide whether to answer.+ *+ * The prefixes are only two bytes each, so they identify nothing on their own — they are a+ * bloom-filter-style hint, not an identity. They are decoded here purely so a capture can be+ * correlated across adverts.+ */+data class AirDropBeacon(+    val version: Int,+    val appleIdHash: ByteArray,+    val phoneHash: ByteArray,+    val emailHash: ByteArray,+    val email2Hash: ByteArray,+) {+    /** The four contact-hash prefixes that are actually populated (Apple zero-fills unused slots). */+    fun populatedHashes(): List<String> =+        listOf(+            "appleId" to appleIdHash,+            "phone" to phoneHash,+            "email" to emailHash,+            "email2" to email2Hash,+        ).filter { (_, h) -> h.any { it != 0.toByte() } }+            .map { (label, h) -> "$label=${h.toHex()}" }++    override fun equals(other: Any?): Boolean = this === other || (+        other is AirDropBeacon &&+            version == other.version &&+            appleIdHash.contentEquals(other.appleIdHash) &&+            phoneHash.contentEquals(other.phoneHash) &&+            emailHash.contentEquals(other.emailHash) &&+            email2Hash.contentEquals(other.email2Hash)+        )++    override fun hashCode(): Int {+        var result = version+        result = 31 * result + appleIdHash.contentHashCode()+        result = 31 * result + phoneHash.contentHashCode()+        result = 31 * result + emailHash.contentHashCode()+        result = 31 * result + email2Hash.contentHashCode()+        return result+    }++    companion object {+        private const val VALUE_LENGTH = 18+        private const val VERSION_OFFSET = 8++        /** Decode a `0x05` TLV value, or null if it is not the expected 18-byte shape. */+        fun parse(value: ByteArray): AirDropBeacon? {+            if (value.size < VALUE_LENGTH) return null+            fun pair(at: Int) = value.copyOfRange(at, at + 2)+            return AirDropBeacon(+                version = value[VERSION_OFFSET].toInt() and 0xFF,+                appleIdHash = pair(VERSION_OFFSET + 1),+                phoneHash = pair(VERSION_OFFSET + 3),+                emailHash = pair(VERSION_OFFSET + 5),+                email2Hash = pair(VERSION_OFFSET + 7),+            )+        }+    }+}++/**+ * A single sighting of an Apple device's manufacturer-data advertisement.+ *+ * [address] is the BLE address as reported by the scanner. Apple devices rotate a resolvable+ * private address every ~15 minutes, so it is a session key and not a device identity — do+ * not persist it or treat two different addresses as two different phones.+ */+data class AppleBeaconSighting(+    val address: String,+    val rssi: Int,+    val localName: String?,+    val tlvs: List<AppleTlv>,+    val raw: ByteArray,+    val seenAtMs: Long,+) {+    /** The decoded AirDrop record, when this advert carried one. */+    val airDrop: AirDropBeacon?+        get() = tlvs.firstOrNull { it.type == APPLE_TLV_AIRDROP }?.let { AirDropBeacon.parse(it.value) }++    /** True when this device currently has an AirDrop share sheet open. */+    val isAirDropping: Boolean get() = airDrop != null++    override fun equals(other: Any?): Boolean = this === other || (+        other is AppleBeaconSighting &&+            address == other.address &&+            tlvs == other.tlvs+        )++    override fun hashCode(): Int = 31 * address.hashCode() + tlvs.hashCode()+}++internal fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }++/**+ * Decode Apple's manufacturer-specific data into its TLV records.+ *+ * The blob is a bare sequence of `type, length, value` triples with no header. A record whose+ * declared length runs past the end of the buffer terminates the parse rather than throwing:+ * BLE adverts get truncated by the controller, and a partial trailing record is normal.+ */+fun parseAppleTlvs(data: ByteArray): List<AppleTlv> {+    val out = mutableListOf<AppleTlv>()+    var i = 0+    while (i + 1 < data.size) {+        val type = data[i].toInt() and 0xFF+        val length = data[i + 1].toInt() and 0xFF+        val valueStart = i + 2+        val valueEnd = valueStart + length+        if (valueEnd > data.size) break+        out.add(AppleTlv(type, data.copyOfRange(valueStart, valueEnd)))+        i = valueEnd+    }+    return out+}++/**+ * Passive BLE observer for Apple continuity beacons, and specifically for AirDrop's `0x05`+ * record.+ *+ * ## What this can and cannot establish+ *+ * This is **reconnaissance, not a transport**. Seeing an AirDrop beacon proves a nearby Apple+ * device has its share sheet open and is soliciting receivers; it does not make this device+ * answerable. AirDrop's beacon exists only to wake nearby receivers' radios — the actual+ * discovery (`_airdrop._tcp`) and transfer (`HTTPS` `/Discover`, `/Ask`, `/Upload`) happen on+ * a peer-to-peer Wi-Fi link, not over BLE, and nothing in the beacon carries an address that+ * can be dialled.+ *+ * It exists so that the peer-to-peer link layer AirDrop actually uses can be identified+ * empirically, by correlating "an iPhone is beaconing AirDrop right now" against what+ * [WifiDirectProbe] and the mDNS browse see at the same instant. That correlation is the only+ * way to settle the question from an Android device; see `AIRDROP_FINDINGS.md`.+ *+ * Needs [Manifest.permission.BLUETOOTH_SCAN]. Declared `neverForLocation`, and nothing here+ * derives position.+ */+class AppleBeaconScanner(private val context: Context) {++    private val bluetoothManager: BluetoothManager? =+        context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager+    private val adapter: BluetoothAdapter? get() = bluetoothManager?.adapter++    private var scanCallback: ScanCallback? = null++    private val _sightings = MutableStateFlow<Map<String, AppleBeaconSighting>>(emptyMap())++    /** Latest sighting per BLE address. Keyed on a rotating address, so entries are short-lived. */+    val sightings: StateFlow<Map<String, AppleBeaconSighting>> = _sightings.asStateFlow()++    private fun hasPermission(permission: String): Boolean =+        ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED++    /**+     * Observe every Apple manufacturer-data advertisement in range.+     *+     * Filters on the company ID only, not on the AirDrop type byte. Apple packs several TLVs+     * into one advert in no guaranteed order, so a data-prefix filter anchored at offset 0+     * would silently miss any advert where AirDrop is not the first record. Filtering broadly+     * and decoding in software costs a few extra callbacks and cannot drop a match.+     */+    fun scan(): Flow<AppleBeaconSighting> = callbackFlow {+        // Point-in-time measurement: a beacon seen during a previous run is not evidence about+        // what is in range now.+        _sightings.value = emptyMap()+        if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN)) {+            Log.w(TAG, "scan denied: missing BLUETOOTH_SCAN")+            close()+            return@callbackFlow+        }+        val btAdapter = adapter ?: run {+            Log.w(TAG, "no BluetoothAdapter")+            close()+            return@callbackFlow+        }+        if (!btAdapter.isEnabled) {+            Log.w(TAG, "Bluetooth disabled")+            close()+            return@callbackFlow+        }+        val scanner = btAdapter.bluetoothLeScanner ?: run {+            Log.w(TAG, "bluetoothLeScanner null")+            close()+            return@callbackFlow+        }++        val filters = listOf(+            ScanFilter.Builder().setManufacturerData(APPLE_COMPANY_ID, ByteArray(0)).build(),+        )+        // Same settings as the Nearby Connections scan: setLegacy(false) is what makes+        // extended advertisements visible at all, and Apple devices do use them.+        val settings = ScanSettings.Builder()+            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)+            .setLegacy(false)+            .setPhy(ScanSettings.PHY_LE_ALL_SUPPORTED)+            .build()++        val callback = object : ScanCallback() {+            override fun onScanResult(callbackType: Int, result: ScanResult) {+                val record = result.scanRecord ?: return+                val data = record.getManufacturerSpecificData(APPLE_COMPANY_ID) ?: return+                val address = result.device?.address ?: return+                val tlvs = parseAppleTlvs(data)+                if (tlvs.isEmpty()) return+                val sighting = AppleBeaconSighting(+                    address = address,+                    rssi = result.rssi,+                    localName = record.deviceName,+                    tlvs = tlvs,+                    raw = data,+                    seenAtMs = System.currentTimeMillis(),+                )+                // Log only when the TLV set changes. An iPhone re-advertises several times a+                // second and an unconditional log buries the one transition that matters.+                val previous = _sightings.value[address]+                _sightings.value = _sightings.value + (address to sighting)+                if (previous == null || previous.tlvs != tlvs) {+                    val airDrop = sighting.airDrop+                    if (airDrop != null) {+                        Log.i(+                            TAG,+                            "AIRDROP beacon from $address rssi=${result.rssi} " ++                                "v${airDrop.version} ${airDrop.populatedHashes()} raw=${data.toHex()}",+                        )+                    } else {+                        Log.d(+                            TAG,+                            "apple beacon from $address rssi=${result.rssi} " ++                                tlvs.joinToString(" "),+                        )+                    }+                }+                trySend(sighting)+            }++            override fun onScanFailed(errorCode: Int) {+                Log.w(TAG, "Apple beacon scan failed: $errorCode")+                close()+            }+        }+        scanCallback = callback+        try {+            @SuppressLint("MissingPermission")+            fun doStart() = scanner.startScan(filters, settings, callback)+            doStart()+            Log.i(TAG, "scanning for Apple manufacturer data (0x%04x)".format(APPLE_COMPANY_ID))+        } catch (e: Exception) {+            Log.w(TAG, "startScan threw", e)+            close(e)+            return@callbackFlow+        }+        awaitClose {+            @SuppressLint("MissingPermission")+            fun stopIfPermitted() {+                if (hasPermission(Manifest.permission.BLUETOOTH_SCAN)) {+                    try {+                        scanner.stopScan(callback)+                    } catch (_: Exception) {+                    }+                }+            }+            stopIfPermitted()+            scanCallback = null+            Log.d(TAG, "Apple beacon scan stopped")+        }+    }++    @SuppressLint("MissingPermission")+    fun stop() {+        val cb = scanCallback ?: return+        if (!hasPermission(Manifest.permission.BLUETOOTH_SCAN)) return+        val scanner = adapter?.bluetoothLeScanner ?: return+        try {+            scanner.stopScan(cb)+        } catch (_: Exception) {+        }+        scanCallback = null+    }++    /** Drop sightings not refreshed within [maxAgeMs]; addresses rotate, so the map must not grow. */+    fun expire(maxAgeMs: Long) {+        val cutoff = System.currentTimeMillis() - maxAgeMs+        _sightings.value = _sightings.value.filterValues { it.seenAtMs >= cutoff }+    }+}
share/src/main/java/com/vayunmathur/share/platform/discovery/apple/WifiDirectProbe.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/WifiDirectProbe.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/WifiDirectProbe.ktnew file mode 100644index 0000000000..fcc1199372--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/apple/WifiDirectProbe.kt@@ -0,0 +1,350 @@+package com.vayunmathur.share.platform.discovery.apple++import android.Manifest+import android.annotation.SuppressLint+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.content.pm.PackageManager+import android.net.wifi.p2p.WifiP2pDevice+import android.net.wifi.p2p.WifiP2pDeviceList+import android.net.wifi.p2p.WifiP2pManager+import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest+import android.os.Build+import android.os.Looper+import android.util.Log+import androidx.core.content.ContextCompat+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.launch++private const val TAG = "WifiDirectProbe"++/** A Wi-Fi Direct peer, flattened to the fields worth logging. */+data class P2pPeer(+    val deviceName: String,+    val deviceAddress: String,+    val primaryDeviceType: String?,+    val secondaryDeviceType: String?,+    val status: Int,+    val isGroupOwner: Boolean,+    val seenAtMs: Long,+) {+    val statusName: String+        get() = when (status) {+            WifiP2pDevice.CONNECTED -> "CONNECTED"+            WifiP2pDevice.INVITED -> "INVITED"+            WifiP2pDevice.FAILED -> "FAILED"+            WifiP2pDevice.AVAILABLE -> "AVAILABLE"+            WifiP2pDevice.UNAVAILABLE -> "UNAVAILABLE"+            else -> "UNKNOWN($status)"+        }+}++/** A DNS-SD service record advertised over Wi-Fi Direct by a peer. */+data class P2pService(+    val instanceName: String,+    val registrationType: String,+    val deviceAddress: String,+    val deviceName: String,+    val txt: Map<String, String> = emptyMap(),+)++/** Everything the probe has observed so far. */+data class P2pObservations(+    val peers: Map<String, P2pPeer> = emptyMap(),+    val services: Map<String, P2pService> = emptyMap(),+    /** Set when the probe could not run at all, with the reason. */+    val unavailableReason: String? = null,+)++/**+ * Wi-Fi Direct (Wi-Fi P2P) peer and DNS-SD service discovery.+ *+ * ## Why this exists+ *+ * To determine, empirically and on real hardware, whether an iPhone soliciting an AirDrop+ * transfer is reachable over Wi-Fi Direct. It is deliberately a *probe* and not a transport:+ * it discovers and logs, and connects to nothing.+ *+ * Run it alongside [AppleBeaconScanner] with an iPhone's share sheet open. The BLE scanner+ * establishes the ground truth that the phone is beaconing AirDrop *right now*; this probe+ * establishes whether that same phone is simultaneously visible as a Wi-Fi Direct peer, and+ * whether it publishes any DNS-SD service (an `_airdrop._tcp` record in particular) over that+ * link. Those two observations together are what settle the transport question — see+ * `AIRDROP_FINDINGS.md` for how to run it and what was actually observed.+ *+ * A DNS-SD request is issued for *all* service types rather than for `_airdrop._tcp`+ * specifically, because a negative result on a narrow filter is uninformative: it cannot+ * distinguish "the peer publishes nothing" from "the peer publishes something under a name we+ * did not ask for".+ *+ * ## Permissions+ *+ * On API 33+ [Manifest.permission.NEARBY_WIFI_DEVICES] covers both peer and service+ * discovery. On API 31–32 the platform requires [Manifest.permission.ACCESS_FINE_LOCATION]+ * instead, which `:share` deliberately does not request, so the probe reports itself+ * unavailable there rather than adding a location permission for a diagnostic.+ */+class WifiDirectProbe(private val context: Context) {++    private val manager: WifiP2pManager? =+        context.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager++    private val _observations = MutableStateFlow(P2pObservations())+    val observations: StateFlow<P2pObservations> = _observations.asStateFlow()++    private fun hasPermission(permission: String): Boolean =+        ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED++    /**+     * Why the probe cannot run, or null if it can.+     *+     * Reported rather than thrown: "Wi-Fi Direct is unsupported here" is itself a finding, and+     * a probe that silently produces nothing is indistinguishable from a probe that ran and+     * found nothing — which is exactly the distinction this whole exercise turns on.+     */+    private fun unavailableReason(): String? = when {+        manager == null -> "no WifiP2pManager (Wi-Fi Direct unsupported on this device)"+        !context.packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT) ->+            "device does not declare FEATURE_WIFI_DIRECT"+        Build.VERSION.SDK_INT >= 33 && !hasPermission(Manifest.permission.NEARBY_WIFI_DEVICES) ->+            "missing NEARBY_WIFI_DEVICES"+        Build.VERSION.SDK_INT < 33 ->+            "API ${Build.VERSION.SDK_INT} requires ACCESS_FINE_LOCATION for P2P discovery, " ++                "which :share does not request"+        else -> null+    }++    @SuppressLint("MissingPermission")+    fun probe(): Flow<P2pObservations> = callbackFlow {+        // Start from nothing on every run: observations from a previous run say nothing about+        // what is in range now, and this probe is read as a point-in-time measurement.+        _observations.value = P2pObservations()+        val reason = unavailableReason()+        if (reason != null || manager == null) {+            val why = reason ?: "no WifiP2pManager"+            Log.w(TAG, "Wi-Fi Direct probe unavailable: $why")+            _observations.value = _observations.value.copy(unavailableReason = why)+            trySend(_observations.value)+            close()+            return@callbackFlow+        }++        val channel = manager.initialize(context, Looper.getMainLooper(), null) ?: run {+            Log.w(TAG, "WifiP2pManager.initialize returned null")+            _observations.value = _observations.value.copy(unavailableReason = "initialize failed")+            trySend(_observations.value)+            close()+            return@callbackFlow+        }++        fun publish() {+            trySend(_observations.value)+        }++        // ----- peers -----------------------------------------------------+        val peerListener = WifiP2pManager.PeerListListener { list: WifiP2pDeviceList? ->+            val now = System.currentTimeMillis()+            val peers = list?.deviceList.orEmpty().associate { d ->+                d.deviceAddress to P2pPeer(+                    deviceName = d.deviceName ?: "",+                    deviceAddress = d.deviceAddress ?: "",+                    primaryDeviceType = d.primaryDeviceType,+                    secondaryDeviceType = d.secondaryDeviceType,+                    status = d.status,+                    isGroupOwner = d.isGroupOwner,+                    seenAtMs = now,+                )+            }+            // Replace, do not merge. requestPeers reports the complete current list, so a peer+            // that has gone away is absent from it — and retaining it would turn "no peers while+            // AirDrop is beaconing" into a false sighting, which is the one mistake this probe+            // must not make.+            val previous = _observations.value.peers+            _observations.value = _observations.value.copy(peers = peers)+            peers.values.filter { previous[it.deviceAddress]?.status != it.status }.forEach { p ->+                Log.i(+                    TAG,+                    "P2P peer \"${p.deviceName}\" ${p.deviceAddress} ${p.statusName} " ++                        "primaryType=${p.primaryDeviceType} groupOwner=${p.isGroupOwner}",+                )+            }+            (previous.keys - peers.keys).forEach { Log.i(TAG, "P2P peer $it gone") }+            publish()+        }++        val receiver = object : BroadcastReceiver() {+            @SuppressLint("MissingPermission")+            override fun onReceive(ctx: Context?, intent: Intent?) {+                when (intent?.action) {+                    WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION ->+                        try {+                            manager.requestPeers(channel, peerListener)+                        } catch (e: SecurityException) {+                            Log.w(TAG, "requestPeers denied", e)+                        }++                    WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {+                        val enabled = intent.getIntExtra(+                            WifiP2pManager.EXTRA_WIFI_STATE,+                            WifiP2pManager.WIFI_P2P_STATE_DISABLED,+                        ) == WifiP2pManager.WIFI_P2P_STATE_ENABLED+                        Log.i(TAG, "Wi-Fi P2P ${if (enabled) "enabled" else "disabled"}")+                        if (!enabled) {+                            _observations.value = _observations.value+                                .copy(unavailableReason = "Wi-Fi Direct is turned off")+                            publish()+                        }+                    }+                }+            }+        }+        val filter = IntentFilter().apply {+            addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)+            addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)+        }+        ContextCompat.registerReceiver(+            context,+            receiver,+            filter,+            ContextCompat.RECEIVER_NOT_EXPORTED,+        )++        // ----- DNS-SD services -------------------------------------------+        val serviceListener = WifiP2pManager.DnsSdServiceResponseListener {+                instanceName, registrationType, srcDevice ->+            val key = "$instanceName|$registrationType|${srcDevice?.deviceAddress}"+            val svc = P2pService(+                instanceName = instanceName ?: "",+                registrationType = registrationType ?: "",+                deviceAddress = srcDevice?.deviceAddress ?: "",+                deviceName = srcDevice?.deviceName ?: "",+            )+            val existing = _observations.value.services[key]+            _observations.value = _observations.value.copy(+                services = _observations.value.services + (key to (existing ?: svc)),+            )+            Log.i(+                TAG,+                "P2P DNS-SD service \"$instanceName\" type=$registrationType " ++                    "from ${srcDevice?.deviceName} ${srcDevice?.deviceAddress}",+            )+            publish()+        }+        val txtListener = WifiP2pManager.DnsSdTxtRecordListener {+                fullDomainName, txtRecordMap, srcDevice ->+            Log.i(+                TAG,+                "P2P DNS-SD TXT $fullDomainName from ${srcDevice?.deviceAddress} = $txtRecordMap",+            )+            // Attach the TXT map to whichever service record it belongs to. The domain name is+            // the only correlator the two callbacks share, and they arrive in either order.+            val instance = fullDomainName?.substringBefore('.') ?: return@DnsSdTxtRecordListener+            _observations.value = _observations.value.copy(+                services = _observations.value.services.mapValues { (_, svc) ->+                    if (svc.instanceName == instance && svc.deviceAddress == srcDevice?.deviceAddress) {+                        svc.copy(txt = txtRecordMap.orEmpty())+                    } else {+                        svc+                    }+                },+            )+            publish()+        }+        manager.setDnsSdResponseListeners(channel, serviceListener, txtListener)++        fun actionListener(what: String) = object : WifiP2pManager.ActionListener {+            override fun onSuccess() {+                Log.i(TAG, "$what: started")+            }++            override fun onFailure(reasonCode: Int) {+                val name = when (reasonCode) {+                    WifiP2pManager.P2P_UNSUPPORTED -> "P2P_UNSUPPORTED"+                    WifiP2pManager.ERROR -> "ERROR"+                    WifiP2pManager.BUSY -> "BUSY"+                    WifiP2pManager.NO_SERVICE_REQUESTS -> "NO_SERVICE_REQUESTS"+                    else -> "reason=$reasonCode"+                }+                Log.w(TAG, "$what: failed ($name)")+            }+        }++        // newInstance() with no arguments asks for every service type; see the class KDoc for+        // why a narrow _airdrop._tcp filter would not be a usable negative result.+        val serviceRequest = WifiP2pDnsSdServiceRequest.newInstance()++        fun startDiscovery() {+            try {+                manager.discoverServices(channel, actionListener("discoverServices"))+                manager.discoverPeers(channel, actionListener("discoverPeers"))+            } catch (e: SecurityException) {+                Log.w(TAG, "P2P discovery denied", e)+                _observations.value =+                    _observations.value.copy(unavailableReason = "denied: ${e.message}")+                publish()+            }+        }++        try {+            manager.addServiceRequest(channel, serviceRequest, actionListener("addServiceRequest"))+        } catch (e: SecurityException) {+            Log.w(TAG, "addServiceRequest denied", e)+            _observations.value = _observations.value.copy(unavailableReason = "denied: ${e.message}")+            publish()+        }++        // Re-issue discovery on a timer instead of once. A single discoverPeers() covers one scan+        // cycle and then lapses, so a one-shot call can miss a peer that appeared seconds later —+        // and this probe's whole value rests on "no peer while AirDrop was beaconing" being a+        // real absence rather than a scan that had already finished.+        launch {+            while (true) {+                startDiscovery()+                delay(REDISCOVER_INTERVAL_MS)+            }+        }++        publish()++        awaitClose {+            try {+                context.unregisterReceiver(receiver)+            } catch (_: IllegalArgumentException) {+            }+            @SuppressLint("MissingPermission")+            fun cleanup() {+                try {+                    manager.removeServiceRequest(channel, serviceRequest, actionListener("removeServiceRequest"))+                    manager.stopPeerDiscovery(channel, actionListener("stopPeerDiscovery"))+                } catch (_: Exception) {+                }+            }+            cleanup()+            // close() releases the framework-side channel; without it the next probe on the+            // same process silently gets BUSY.+            try {+                channel.close()+            } catch (_: Exception) {+            }+            Log.d(TAG, "Wi-Fi Direct probe stopped")+        }+    }++    private companion object {+        /**+         * How often peer and service discovery are re-issued.+         *+         * Wi-Fi P2P discovery cycles the social channels and then lapses; 10s keeps a scan+         * effectively always in flight without thrashing the radio.+         */+        const val REDISCOVER_INTERVAL_MS = 10_000L+    }+}
share/src/main/java/com/vayunmathur/share/ui/AirDropProbeScreen.kt
diff --git a/share/src/main/java/com/vayunmathur/share/ui/AirDropProbeScreen.kt b/share/src/main/java/com/vayunmathur/share/ui/AirDropProbeScreen.ktnew file mode 100644index 0000000000..be5e1819c6--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/ui/AirDropProbeScreen.kt@@ -0,0 +1,234 @@+package com.vayunmathur.share.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.produceState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.share.R+import com.vayunmathur.share.Route+import com.vayunmathur.share.platform.discovery.apple.AirDropProbe+import com.vayunmathur.share.platform.discovery.apple.AirDropProbeReport++/** Page wrapper for [AirDropProbeScreen], with the top bar's back button wired to [backStack]. */+@Composable+fun AirDropProbePage(backStack: NavBackStack<Route>) {+    AppScaffold(+        title = stringResource(R.string.share_airdrop_probe),+        backStack = backStack,+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        AirDropProbeScreen(modifier = Modifier.fillMaxSize().padding(padding))+    }+}++/**+ * Diagnostic screen for [AirDropProbe].+ *+ * Exists so the probe can be run on a real handset next to a real iPhone and the result read+ * off the screen instead of out of logcat. Deliberately plain: it renders the report verbatim,+ * including raw hex, because the point is to see exactly what arrived.+ */+@Composable+fun AirDropProbeScreen(modifier: Modifier = Modifier) {+    val context = LocalContext.current+    var running by remember { mutableStateOf(false) }+    val probe = remember { AirDropProbe(context) }++    // produceState keyed on `running` is what ties the radios to the toggle: flipping it off+    // cancels the producer, which cancels the probe flow, which stops the BLE scan and P2P+    // discovery. Leaving those running after the user stopped the probe would drain the+    // battery invisibly.+    val report by produceState<AirDropProbeReport?>(initialValue = null, running) {+        if (!running) {+            value = null+            return@produceState+        }+        probe.run().collect { value = it }+    }++    LazyColumn(+        modifier = modifier+            .fillMaxSize()+            .padding(horizontal = 16.dp, vertical = 12.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        item {+            Card(modifier = Modifier.fillMaxWidth()) {+                Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                    Text(+                        stringResource(R.string.share_airdrop_probe_idle),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.outline,+                    )+                    Text(+                        stringResource(R.string.share_airdrop_probe_howto),+                        style = MaterialTheme.typography.bodySmall,+                    )+                    Row(+                        modifier = Modifier.fillMaxWidth(),+                        horizontalArrangement = Arrangement.spacedBy(8.dp),+                        verticalAlignment = Alignment.CenterVertically,+                    ) {+                        if (running) {+                            Button(onClick = { running = false }) {+                                Text(stringResource(R.string.share_airdrop_probe_stop))+                            }+                            CircularProgressIndicator()+                        } else {+                            OutlinedButton(onClick = { running = true }) {+                                Text(stringResource(R.string.share_airdrop_probe_start))+                            }+                        }+                    }+                }+            }+        }++        val current = report+        if (current == null) {+            item {+                Card(modifier = Modifier.fillMaxWidth()) {+                    Text(+                        stringResource(R.string.share_airdrop_probe_none),+                        modifier = Modifier.padding(16.dp),+                        color = MaterialTheme.colorScheme.outline,+                    )+                }+            }+            return@LazyColumn+        }++        item {+            Card(modifier = Modifier.fillMaxWidth()) {+                Text(+                    current.summary().trimEnd(),+                    modifier = Modifier.padding(16.dp),+                    style = MaterialTheme.typography.bodySmall,+                    fontFamily = FontFamily.Monospace,+                )+            }+        }++        item {+            ProbeSection(stringResource(R.string.share_airdrop_probe_beacons)) {+                if (current.appleBeacons.isEmpty()) {+                    Text(+                        stringResource(R.string.share_airdrop_probe_none),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.outline,+                    )+                }+                current.appleBeacons.forEach { beacon ->+                    val label = if (beacon.isAirDropping) "AIRDROP" else "apple"+                    Text(+                        "$label ${beacon.address} rssi=${beacon.rssi}",+                        style = MaterialTheme.typography.bodySmall,+                        fontFamily = FontFamily.Monospace,+                        color = if (beacon.isAirDropping) {+                            MaterialTheme.colorScheme.primary+                        } else {+                            MaterialTheme.colorScheme.outline+                        },+                    )+                    beacon.tlvs.forEach { tlv ->+                        Text(+                            "  $tlv",+                            style = MaterialTheme.typography.labelSmall,+                            fontFamily = FontFamily.Monospace,+                            color = MaterialTheme.colorScheme.outline,+                        )+                    }+                }+            }+        }++        item {+            ProbeSection(stringResource(R.string.share_airdrop_probe_p2p)) {+                val reason = current.p2p.unavailableReason+                if (reason != null) {+                    Text(+                        reason,+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.error,+                    )+                }+                if (current.p2p.peers.isEmpty() && reason == null) {+                    Text(+                        stringResource(R.string.share_airdrop_probe_none),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.outline,+                    )+                }+                current.p2p.peers.values.forEach { peer ->+                    Text(+                        "peer \"${peer.deviceName}\" ${peer.deviceAddress} ${peer.statusName}",+                        style = MaterialTheme.typography.bodySmall,+                        fontFamily = FontFamily.Monospace,+                    )+                }+                current.p2p.services.values.forEach { svc ->+                    Text(+                        "svc ${svc.instanceName} ${svc.registrationType} ${svc.txt}",+                        style = MaterialTheme.typography.bodySmall,+                        fontFamily = FontFamily.Monospace,+                    )+                }+            }+        }++        item {+            ProbeSection(stringResource(R.string.share_airdrop_probe_mdns)) {+                if (current.mdns.isEmpty()) {+                    Text(+                        stringResource(R.string.share_airdrop_probe_none),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.outline,+                    )+                }+                current.mdns.forEach { record ->+                    Text(+                        "${record.serviceType} \"${record.serviceName}\" " ++                            if (record.resolved) "${record.host}:${record.port}" else "(unresolved)",+                        style = MaterialTheme.typography.bodySmall,+                        fontFamily = FontFamily.Monospace,+                    )+                }+            }+        }+    }+}++@Composable+private fun ProbeSection(title: String, content: @Composable () -> Unit) {+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+            Text(title, style = MaterialTheme.typography.titleSmall)+            content()+        }+    }+}
share/src/main/java/com/vayunmathur/share/ui/ShareSendScreen.kt
diff --git a/share/src/main/java/com/vayunmathur/share/ui/ShareSendScreen.kt b/share/src/main/java/com/vayunmathur/share/ui/ShareSendScreen.ktindex 5b1fefe4d0..c2c63073af 100644--- a/share/src/main/java/com/vayunmathur/share/ui/ShareSendScreen.kt+++ b/share/src/main/java/com/vayunmathur/share/ui/ShareSendScreen.kt@@ -19,6 +19,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CircularProgressIndicator@@ -26,6 +27,8 @@ import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.share.R import com.vayunmathur.share.network.transport.Connection import com.vayunmathur.share.platform.discovery.DiscoverySource@@ -35,6 +38,33 @@ import com.vayunmathur.share.platform.ShareViewModel import com.vayunmathur.share.platform.ShareActions import com.vayunmathur.share.platform.SendUiState +/**+ * The whole in-app surface: sending.+ *+ * Receiving has no screen. It is driven by notifications and turned on and off from a Quick+ * Settings tile, so it works when the app has never been opened.+ *+ * [onOpenAirDropProbe] opens the AirDrop transport diagnostic, which is not part of the send+ * flow and shares nothing with it.+ */+@Composable+fun ShareSendPage(viewModel: ShareViewModel, onOpenAirDropProbe: () -> Unit) {+    AppScaffold(+        title = stringResource(R.string.app_name),+        actions = {+            TextButton(onClick = onOpenAirDropProbe) {+                Text(stringResource(R.string.share_airdrop_probe))+            }+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        ShareSendScreen(+            viewModel = viewModel,+            modifier = Modifier.fillMaxSize().padding(padding),+        )+    }+}+ @Composable fun ShareSendScreen(     viewModel: ShareViewModel,
share/src/main/res/values/strings.xml
diff --git a/share/src/main/res/values/strings.xml b/share/src/main/res/values/strings.xmlindex 95559abf0c..a51ec45675 100644--- a/share/src/main/res/values/strings.xml+++ b/share/src/main/res/values/strings.xml@@ -69,4 +69,16 @@     <string name="share_popup_title">Send to a nearby device</string>     <string name="share_popup_no_devices">No devices found yet. Keep the other device visible.</string>     <string name="share_popup_permission_needed">Nearby Share needs Bluetooth and Wi-Fi permissions to find nearby devices.</string>++    <!-- AirDrop transport probe (diagnostic) -->+    <string name="share_airdrop_probe">AirDrop probe</string>+    <string name="share_airdrop_probe_open">AirDrop probe…</string>+    <string name="share_airdrop_probe_start">Start probe</string>+    <string name="share_airdrop_probe_stop">Stop probe</string>+    <string name="share_airdrop_probe_idle">Scans for Apple\'s AirDrop BLE beacon, Wi-Fi Direct peers and Apple mDNS records at the same time, to establish which transports an AirDropping iPhone is actually reachable on from this device.</string>+    <string name="share_airdrop_probe_howto">Open the share sheet on the iPhone, pick a file, and leave the AirDrop picker on screen while the probe runs. Set AirDrop to Everyone.</string>+    <string name="share_airdrop_probe_beacons">Apple BLE beacons</string>+    <string name="share_airdrop_probe_p2p">Wi-Fi Direct</string>+    <string name="share_airdrop_probe_mdns">Apple mDNS on Wi-Fi</string>+    <string name="share_airdrop_probe_none">Nothing seen yet.</string> </resources>
share/src/test/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScannerTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScannerTest.kt b/share/src/test/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScannerTest.ktnew file mode 100644index 0000000000..a57c85fe70--- /dev/null+++ b/share/src/test/java/com/vayunmathur/share/platform/discovery/apple/AppleBeaconScannerTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.share.platform.discovery.apple++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Tests for the Apple manufacturer-data TLV decoder.+ *+ * Pure byte handling, so it runs on the JVM. Worth covering because the decoder is the only+ * logic in the AirDrop probe that can be wrong *silently*: a mis-parsed advert produces a+ * plausible-looking result rather than an error, and the whole point of the probe is that its+ * negative result be trustworthy.+ */+class AppleBeaconScannerTest {++    private fun bytes(vararg values: Int): ByteArray =+        ByteArray(values.size) { values[it].toByte() }++    /** An 18-byte AirDrop value: 8 zero bytes, version, four 2-byte hashes, terminator. */+    private fun airDropValue(+        version: Int = 0x01,+        appleId: Int = 0xAABB,+        phone: Int = 0xCCDD,+        email: Int = 0x0000,+        email2: Int = 0x0000,+    ): ByteArray = bytes(+        0, 0, 0, 0, 0, 0, 0, 0,+        version,+        appleId shr 8, appleId and 0xFF,+        phone shr 8, phone and 0xFF,+        email shr 8, email and 0xFF,+        email2 shr 8, email2 and 0xFF,+        0,+    )++    @Test+    fun `decodes a single TLV`() {+        val tlvs = parseAppleTlvs(bytes(0x10, 0x02, 0xAA, 0xBB))+        assertEquals(1, tlvs.size)+        assertEquals(0x10, tlvs[0].type)+        assertEquals("NearbyInfo", tlvs[0].name)+        assertEquals("aabb", tlvs[0].value.toHex())+    }++    @Test+    fun `decodes several TLVs in one advert`() {+        // AirDrop is deliberately not first: the scanner must not depend on its position, which+        // is why the scan filter matches the company ID rather than a data prefix.+        val data = bytes(0x10, 0x02, 0x01, 0x02) ++            bytes(APPLE_TLV_AIRDROP, 0x12) + airDropValue() ++            bytes(0x0C, 0x01, 0x09)+        val tlvs = parseAppleTlvs(data)+        assertEquals(listOf(0x10, APPLE_TLV_AIRDROP, 0x0C), tlvs.map { it.type })+        assertEquals(18, tlvs[1].value.size)+    }++    @Test+    fun `stops at a length running past the buffer instead of throwing`() {+        // BLE adverts get truncated by the controller, so a partial trailing record is normal+        // and must not lose the records that already parsed.+        val tlvs = parseAppleTlvs(bytes(0x10, 0x02, 0xAA, 0xBB, 0x05, 0x12, 0x00))+        assertEquals(1, tlvs.size)+        assertEquals(0x10, tlvs[0].type)+    }++    @Test+    fun `ignores a trailing type byte with no length`() {+        val tlvs = parseAppleTlvs(bytes(0x10, 0x02, 0xAA, 0xBB, 0x05))+        assertEquals(1, tlvs.size)+    }++    @Test+    fun `empty data yields no TLVs`() {+        assertTrue(parseAppleTlvs(ByteArray(0)).isEmpty())+    }++    @Test+    fun `zero-length TLV is kept and does not stall the parse`() {+        val tlvs = parseAppleTlvs(bytes(0x0B, 0x00, 0x10, 0x01, 0x07))+        assertEquals(listOf(0x0B, 0x10), tlvs.map { it.type })+        assertEquals(0, tlvs[0].value.size)+    }++    @Test+    fun `parses the AirDrop record fields`() {+        val beacon = AirDropBeacon.parse(airDropValue(version = 0x01))+        requireNotNull(beacon)+        assertEquals(0x01, beacon.version)+        assertEquals("aabb", beacon.appleIdHash.toHex())+        assertEquals("ccdd", beacon.phoneHash.toHex())+        assertEquals("0000", beacon.emailHash.toHex())+    }++    @Test+    fun `populatedHashes omits the zero-filled slots`() {+        val beacon = AirDropBeacon.parse(airDropValue())+        requireNotNull(beacon)+        // Apple zero-fills unused contact slots; reporting them as hashes would invent senders.+        assertEquals(listOf("appleId=aabb", "phone=ccdd"), beacon.populatedHashes())+    }++    @Test+    fun `rejects an AirDrop value that is too short`() {+        assertNull(AirDropBeacon.parse(bytes(0, 0, 0, 0, 0, 0, 0, 0, 1)))+    }++    @Test+    fun `a sighting without an AirDrop TLV is not airdropping`() {+        val sighting = sighting(parseAppleTlvs(bytes(0x10, 0x02, 0x01, 0x02)))+        assertNull(sighting.airDrop)+        assertTrue(!sighting.isAirDropping)+    }++    @Test+    fun `a sighting carrying the AirDrop TLV is airdropping`() {+        val data = bytes(APPLE_TLV_AIRDROP, 0x12) + airDropValue()+        val sighting = sighting(parseAppleTlvs(data))+        assertTrue(sighting.isAirDropping)+        assertEquals(0x01, sighting.airDrop?.version)+    }++    @Test+    fun `sightings compare by TLV content so a rescan is not a new observation`() {+        val data = bytes(0x10, 0x02, 0xAA, 0xBB)+        // Same device, same payload, different RSSI and timestamp — the change detection that+        // gates logging keys on content, so this must compare equal.+        val first = sighting(parseAppleTlvs(data), rssi = -40, seenAtMs = 1)+        val second = sighting(parseAppleTlvs(data), rssi = -70, seenAtMs = 9_999)+        assertEquals(first, second)+    }++    private fun sighting(+        tlvs: List<AppleTlv>,+        rssi: Int = -50,+        seenAtMs: Long = 0,+    ) = AppleBeaconSighting(+        address = "AA:BB:CC:DD:EE:FF",+        rssi = rssi,+        localName = null,+        tlvs = tlvs,+        raw = ByteArray(0),+        seenAtMs = seenAtMs,+    )+}