share: AirDrop send/receive with Mosey HAL detection
- Commit
29c772e361919ef8fdda714fdbe58842464d87a7- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 01:54 UTC (1 month ago)
- Parents
d1799ab
Diff
library/aosp-stubs/build.gradle.kts
diff --git a/library/aosp-stubs/build.gradle.kts b/library/aosp-stubs/build.gradle.ktsindex 51cc2ae950..74a3b9ca95 100644--- a/library/aosp-stubs/build.gradle.kts+++ b/library/aosp-stubs/build.gradle.kts@@ -15,8 +15,11 @@ plugins { // are mirrored exactly so javac emits the same invokevirtual + // checkcast as against the real SDK. Inlined `static final` // constant values matter (TYPE_ALLOWED/BLOCKED/TIME_LIMIT are 0/1/2).-// android.nearby.NearbyManager — @SystemApi, ships in the Connectivity mainline module+// android.nearby.NearbyManager - @SystemApi, ships in the Connectivity mainline module // (com.android.tethering); only the powered-off finding surface.+// android.net.Network{Agent,AgentConfig,Provider,Score} - @SystemApi local-network agent surface+// (framework-connectivity); :share registers Mosey's `mosey0`+// AirDrop link with it. Needs NETWORK_FACTORY on a priv-app. // android.os.UpdateEngine{,Callback} — @SystemApi A/B slot writer; only the surface :updater calls. // android.service.euicc.* — @SystemApi eSIM LPA classes; signatures mirror AOSP so // EuiccManagerService overrides the abstract methods exactly.
library/aosp-stubs/src/main/java/android/net/NetworkAgent.java
diff --git a/library/aosp-stubs/src/main/java/android/net/NetworkAgent.java b/library/aosp-stubs/src/main/java/android/net/NetworkAgent.javanew file mode 100644index 0000000000..c4b7761e33--- /dev/null+++ b/library/aosp-stubs/src/main/java/android/net/NetworkAgent.java@@ -0,0 +1,37 @@+package android.net;++import android.content.Context;+import android.os.Looper;++/**+ * Stub of the @SystemApi {@code android.net.NetworkAgent} (framework-connectivity). Only the+ * surface :share's AirDrop link uses: constructing, registering, marking connected and+ * unregistering a local-only network for the Mosey {@code mosey0} interface.+ */+public abstract class NetworkAgent {+ public NetworkAgent(Context context, Looper looper, String logTag, NetworkCapabilities nc,+ LinkProperties lp, NetworkScore score, NetworkAgentConfig config,+ NetworkProvider provider) {+ throw new RuntimeException("Stub!");+ }++ public Network register() {+ throw new RuntimeException("Stub!");+ }++ public void markConnected() {+ throw new RuntimeException("Stub!");+ }++ public void unregister() {+ throw new RuntimeException("Stub!");+ }++ public Network getNetwork() {+ throw new RuntimeException("Stub!");+ }++ public void onNetworkUnwanted() {+ throw new RuntimeException("Stub!");+ }+}
library/aosp-stubs/src/main/java/android/net/NetworkAgentConfig.java
diff --git a/library/aosp-stubs/src/main/java/android/net/NetworkAgentConfig.java b/library/aosp-stubs/src/main/java/android/net/NetworkAgentConfig.javanew file mode 100644index 0000000000..cd6af00b04--- /dev/null+++ b/library/aosp-stubs/src/main/java/android/net/NetworkAgentConfig.java@@ -0,0 +1,22 @@+package android.net;++/** Stub of the @SystemApi {@code android.net.NetworkAgentConfig}; only its builder is used. */+public final class NetworkAgentConfig {+ private NetworkAgentConfig() {+ throw new RuntimeException("Stub!");+ }++ public static final class Builder {+ public Builder() {+ throw new RuntimeException("Stub!");+ }++ public Builder setLegacyTypeName(String legacyTypeName) {+ throw new RuntimeException("Stub!");+ }++ public NetworkAgentConfig build() {+ throw new RuntimeException("Stub!");+ }+ }+}
library/aosp-stubs/src/main/java/android/net/NetworkProvider.java
diff --git a/library/aosp-stubs/src/main/java/android/net/NetworkProvider.java b/library/aosp-stubs/src/main/java/android/net/NetworkProvider.javanew file mode 100644index 0000000000..75c7323d4f--- /dev/null+++ b/library/aosp-stubs/src/main/java/android/net/NetworkProvider.java@@ -0,0 +1,15 @@+package android.net;++import android.content.Context;+import android.os.Looper;++/**+ * Stub of the @SystemApi {@code android.net.NetworkProvider}. Registered through+ * {@code ConnectivityManager.registerNetworkProvider}, which callers reach reflectively so the+ * public {@code ConnectivityManager} is not shadowed here.+ */+public class NetworkProvider {+ public NetworkProvider(Context context, Looper looper, String name) {+ throw new RuntimeException("Stub!");+ }+}
library/aosp-stubs/src/main/java/android/net/NetworkScore.java
diff --git a/library/aosp-stubs/src/main/java/android/net/NetworkScore.java b/library/aosp-stubs/src/main/java/android/net/NetworkScore.javanew file mode 100644index 0000000000..f7207ef6d7--- /dev/null+++ b/library/aosp-stubs/src/main/java/android/net/NetworkScore.java@@ -0,0 +1,26 @@+package android.net;++/**+ * Stub of the @SystemApi {@code android.net.NetworkScore}; only its builder is used. The+ * keep-connected reason is passed as a literal by the caller rather than declared here, so no+ * constant value is baked in from a stub.+ */+public final class NetworkScore {+ private NetworkScore() {+ throw new RuntimeException("Stub!");+ }++ public static final class Builder {+ public Builder() {+ throw new RuntimeException("Stub!");+ }++ public Builder setKeepConnectedReason(int keepConnectedReason) {+ throw new RuntimeException("Stub!");+ }++ public NetworkScore build() {+ throw new RuntimeException("Stub!");+ }+ }+}
share/build.gradle.kts
diff --git a/share/build.gradle.kts b/share/build.gradle.ktsindex 496171f0fc..35fb4415bc 100644--- a/share/build.gradle.kts+++ b/share/build.gradle.kts@@ -28,4 +28,7 @@ rustNativeLib("share_nearby", "share") dependencies { // ViewModel/Compose already via common-conventions-app; explicit lifecycle for clarity. implementation(libs.androidx.lifecycle.viewmodel.ktx)+ // @SystemApi NetworkAgent/NetworkProvider for the Mosey `mosey0` AirDrop link; compile-only,+ // must NOT be packaged. See :library:aosp-stubs.+ compileOnly(project(":library:aosp-stubs")) }
share/src/main/AndroidManifest.xml
diff --git a/share/src/main/AndroidManifest.xml b/share/src/main/AndroidManifest.xmlindex c9d0ee8900..eb5d4e1a78 100644--- a/share/src/main/AndroidManifest.xml+++ b/share/src/main/AndroidManifest.xml@@ -1,6 +1,7 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:tools="http://schemas.android.com/tools">+ xmlns:tools="http://schemas.android.com/tools"+ tools:ignore="ProtectedPermissions"> <!-- Every permission the discovery and transfer paths actually exercise. These were missing@@ -39,6 +40,21 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <!-- AirDrop: link selection reads the active Wi-Fi network and its channel. -->+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />++ <!--+ AirDrop over Google's Mosey (AWDL) HAL, mirroring privapp-permissions-com.google.android.mosey.xml:+ publishing `mosey0` as a local network needs NETWORK_FACTORY, and binding sockets/mDNS to that+ restricted network needs CONNECTIVITY_USE_RESTRICTED_NETWORKS. Granted only when MAOS installs+ :share as a whitelisted priv-app; elsewhere they are inert and AirDrop falls back to Wi-Fi.+ -->+ <uses-permission android:name="android.permission.NETWORK_FACTORY" />+ <uses-permission android:name="android.permission.CREATE_APP_SPECIFIC_NETWORK" />+ <uses-permission android:name="android.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS" />+ <uses-permission android:name="android.permission.MANAGE_WIFI_INTERFACES" />+ <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" />@@ -51,6 +67,11 @@ android:roundIcon="@mipmap/ic_launcher" android:supportsRtl="true" android:theme="@style/Theme.General">+ <!-- Mosey's client library, present on Pixels that ship AirDrop interop. -->+ <uses-library+ android:name="com.google.android.moseylib"+ android:required="false" />+ <activity android:name=".MainActivity" android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"
share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.ktnew file mode 100644index 0000000000..68e8636a51--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.kt@@ -0,0 +1,154 @@+package com.vayunmathur.share.domain.airdrop++/**+ * Typed views of the AirDrop `/Discover` and `/Ask` plists.+ *+ * Field names and value types are the ones Mosey writes (`cbz`, `cdv`, `cbx`, `cdw`), and the+ * parsers are lenient in the way Apple senders need: iOS adds `SenderRecordData`,+ * `FileIcon` and others we ignore, and omits the `TransferID` Mosey adds.+ */+object AirDropMessages {++ const val USER_AGENT = "AirDrop/1.0"+ const val CONTENT_TYPE_PLIST = "application/octet-stream"+ const val CONTENT_TYPE_CPIO = "application/x-cpio"+ const val CONTENT_TYPE_DVZIP = "application/x-dvzip"+ const val CONTENT_TYPE_ZIP = "application/zip"++ /** Mosey's sender drops any receiver whose `Manufacturer` is this, case-insensitively. */+ const val MANUFACTURER_GOOGLE = "Google"++ /** What Mosey and OpenDrop both advertise; Apple peers only check that it parses. */+ val DEFAULT_MEDIA_CAPABILITIES: ByteArray = """{"Version":1}""".toByteArray(Charsets.UTF_8)++ data class DiscoverResponse(+ val receiverComputerName: String,+ val manufacturer: String? = null,+ val mediaCapabilities: ByteArray? = null,+ ) {+ fun toPlist(): Map<String, Any?> = buildMap {+ put("ReceiverComputerName", receiverComputerName)+ mediaCapabilities?.let { put("ReceiverMediaCapabilities", it) }+ manufacturer?.let { put("Manufacturer", it) }+ }++ companion object {+ fun fromPlist(map: Map<String, Any?>): DiscoverResponse? {+ val name = (map["ReceiverComputerName"] as? String)?.takeIf { it.isNotBlank() } ?: return null+ return DiscoverResponse(+ receiverComputerName = name,+ manufacturer = map["Manufacturer"] as? String,+ mediaCapabilities = map["ReceiverMediaCapabilities"] as? ByteArray,+ )+ }+ }+ }++ data class AskFile(+ val fileName: String,+ val fileType: String,+ val fileSize: Long,+ val fileBomPath: String,+ val isDirectory: Boolean = false,+ val fileSubType: String? = null,+ ) {+ fun toPlist(): Map<String, Any?> = buildMap {+ put("ConvertMediaFormats", 0L)+ put("FileIsDirectory", isDirectory)+ put("FileName", fileName)+ put("FileType", fileType)+ fileSubType?.let { put("FileSubType", it) }+ put("FileSize", fileSize)+ put("FileBomPath", fileBomPath)+ put("ShouldConvertMediaFormats", false)+ }++ companion object {+ fun fromPlist(map: Map<*, *>): AskFile? {+ val name = (map["FileName"] as? String)?.takeIf { it.isNotBlank() } ?: return null+ return AskFile(+ fileName = name,+ fileType = map["FileType"] as? String ?: "public.data",+ fileSize = (map["FileSize"] as? Long) ?: -1L,+ fileBomPath = map["FileBomPath"] as? String ?: "./$name",+ isDirectory = map["FileIsDirectory"] as? Boolean ?: false,+ fileSubType = map["FileSubType"] as? String,+ )+ }++ /** A regular file entry, typed from its extension. */+ fun forFile(name: String, size: Long): AskFile = AskFile(+ fileName = name,+ fileType = Uti.forFileName(name).uti,+ fileSize = size,+ fileBomPath = "./$name",+ )+ }+ }++ data class AskRequest(+ val senderComputerName: String,+ val senderModelName: String,+ val senderId: String,+ val files: List<AskFile>,+ val bundleId: String = Uti.DEFAULT_BUNDLE_ID,+ val items: List<String> = emptyList(),+ val transferId: String? = null,+ ) {+ fun toPlist(): Map<String, Any?> = buildMap {+ put("ConvertMediaFormats", false)+ transferId?.let { put("TransferID", mapOf("id" to it)) }+ put("SenderID", senderId)+ put("SenderComputerName", senderComputerName)+ put("SenderModelName", senderModelName)+ put("BundleID", bundleId)+ if (items.isNotEmpty()) put("Items", items)+ put("TransferType", mapOf((if (items.isEmpty()) "files" else "links") to emptyMap<String, Any?>()))+ put("Files", files.map { it.toPlist() })+ }++ /** Sum of announced sizes, treating Apple's "unknown" (negative) as zero. */+ val totalBytes: Long get() = files.sumOf { it.fileSize.coerceAtLeast(0) }++ companion object {+ fun fromPlist(map: Map<String, Any?>): AskRequest? {+ val files = (map["Files"] as? List<*>).orEmpty()+ .mapNotNull { (it as? Map<*, *>)?.let(AskFile::fromPlist) }+ val items = (map["Items"] as? List<*>).orEmpty().filterIsInstance<String>()+ if (files.isEmpty() && items.isEmpty()) return null+ val transferId = when (val t = map["TransferID"]) {+ is String -> t+ is Map<*, *> -> t["id"] as? String+ else -> null+ }+ return AskRequest(+ senderComputerName = (map["SenderComputerName"] as? String)?.takeIf { it.isNotBlank() } ?: "AirDrop",+ senderModelName = map["SenderModelName"] as? String ?: "",+ senderId = map["SenderID"] as? String ?: "",+ files = files,+ bundleId = map["BundleID"] as? String ?: Uti.DEFAULT_BUNDLE_ID,+ items = items,+ transferId = transferId,+ )+ }+ }+ }++ /**+ * The local name to store a received entry under, or null to skip it.+ *+ * Archive names are `./<bom path>`, sometimes under an `NSIRD_AirDrop_<id>` wrapper+ * directory. Anything that would escape the destination is refused, not sanitised.+ */+ fun safeRelativePath(archiveName: String): String? {+ val parts = archiveName.replace('\\', '/').split('/')+ .filter { it.isNotEmpty() && it != "." }+ .dropWhile { it.startsWith("NSIRD_AirDrop") }+ if (parts.isEmpty() || parts.any { it == ".." }) return null+ return parts.joinToString("/")+ }++ /** 6 random bytes as 12 lowercase hex chars, Mosey's shape for `SenderID` and its mDNS name. */+ fun randomShortId(random: java.security.SecureRandom = java.security.SecureRandom()): String =+ ByteArray(6).also(random::nextBytes).joinToString("") { "%02x".format(it) }+}
share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.ktnew file mode 100644index 0000000000..79dd61c99d--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt@@ -0,0 +1,278 @@+package com.vayunmathur.share.domain.airdrop++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer++/**+ * Apple binary property list (`bplist00`) codec — the body format of every AirDrop+ * `/Discover` and `/Ask` request and response.+ *+ * Values map to Kotlin as: `Boolean`, `Long` (every integer width), `Double`, `String`,+ * `ByteArray` (plist data), `List<Any?>` (array) and `Map<String, Any?>` (dict). `Int` is+ * accepted on encode and widened to `Long`. Dates decode to their raw seconds-since-2001+ * `Double`; AirDrop never sends one that matters.+ */+object BinaryPlist {++ private const val MAGIC = "bplist00"+ private const val TRAILER_SIZE = 32++ class FormatException(message: String) : IllegalArgumentException(message)++ fun encode(root: Any?): ByteArray = Encoder().encode(root)++ fun decode(bytes: ByteArray): Any? = Decoder(bytes).decodeRoot()++ /** [decode] for the common case of a dict at the root. */+ @Suppress("UNCHECKED_CAST")+ fun decodeDict(bytes: ByteArray): Map<String, Any?> =+ decode(bytes) as? Map<String, Any?> ?: throw FormatException("root is not a dict")++ private class Encoder {+ private val objects = mutableListOf<Any?>()++ fun encode(root: Any?): ByteArray {+ flatten(root)+ val refSize = sizeFor(objects.size.toLong())+ val out = ByteArrayOutputStream()+ out.write(MAGIC.toByteArray(Charsets.US_ASCII))+ val offsets = LongArray(objects.size)+ objects.forEachIndexed { index, obj ->+ offsets[index] = out.size().toLong()+ // Children were flattened immediately after their parent.+ writeObject(out, obj, refSize, firstChildRef = index + 1)+ }+ val offsetTableOffset = out.size().toLong()+ val offsetSize = sizeFor(offsetTableOffset)+ offsets.forEach { writeSized(out, it, offsetSize) }+ out.write(ByteArray(6))+ out.write(offsetSize)+ out.write(refSize)+ writeSized(out, objects.size.toLong(), 8)+ writeSized(out, 0, 8)+ writeSized(out, offsetTableOffset, 8)+ return out.toByteArray()+ }++ /** Depth-first, matching the order [writeObject] hands out child refs. */+ private fun flatten(value: Any?) {+ objects += value+ when (value) {+ is Map<*, *> -> {+ value.keys.forEach { flatten(it as? String ?: throw FormatException("dict key ${it?.javaClass}")) }+ value.values.forEach { flatten(it) }+ }+ is List<*> -> value.forEach { flatten(it) }+ }+ }++ private fun subtreeSize(value: Any?): Int = 1 + when (value) {+ is Map<*, *> -> value.keys.size + value.values.sumOf { subtreeSize(it) }+ is List<*> -> value.sumOf { subtreeSize(it) }+ else -> 0+ }++ private fun writeObject(out: ByteArrayOutputStream, value: Any?, refSize: Int, firstChildRef: Int) {+ when (value) {+ null -> out.write(0x00)+ is Boolean -> out.write(if (value) 0x09 else 0x08)+ is Int -> writeInt(out, value.toLong())+ is Long -> writeInt(out, value)+ is Double -> {+ out.write(0x23)+ writeSized(out, java.lang.Double.doubleToRawLongBits(value), 8)+ }+ is String -> writeString(out, value)+ is ByteArray -> {+ writeMarker(out, 0x40, value.size)+ out.write(value)+ }+ is List<*> -> {+ writeMarker(out, 0xA0, value.size)+ var ref = firstChildRef+ value.forEach { child ->+ writeSized(out, ref.toLong(), refSize)+ ref += subtreeSize(child)+ }+ }+ is Map<*, *> -> {+ writeMarker(out, 0xD0, value.size)+ var ref = firstChildRef+ value.keys.forEach { _ -> writeSized(out, (ref++).toLong(), refSize) }+ value.values.forEach { child ->+ writeSized(out, ref.toLong(), refSize)+ ref += subtreeSize(child)+ }+ }+ else -> throw FormatException("cannot encode ${value.javaClass.name}")+ }+ }++ private fun writeInt(out: ByteArrayOutputStream, v: Long) {+ val (marker, size) = when (v) {+ in 0L..0xFFL -> 0x10 to 1+ in 0L..0xFFFFL -> 0x11 to 2+ in 0L..0xFFFFFFFFL -> 0x12 to 4+ else -> 0x13 to 8+ }+ out.write(marker)+ writeSized(out, v, size)+ }++ private fun writeString(out: ByteArrayOutputStream, s: String) {+ if (s.all { it.code < 0x80 }) {+ writeMarker(out, 0x50, s.length)+ out.write(s.toByteArray(Charsets.US_ASCII))+ } else {+ writeMarker(out, 0x60, s.length)+ out.write(s.toByteArray(Charsets.UTF_16BE))+ }+ }++ private fun writeMarker(out: ByteArrayOutputStream, type: Int, count: Int) {+ if (count < 0x0F) {+ out.write(type or count)+ } else {+ out.write(type or 0x0F)+ writeInt(out, count.toLong())+ }+ }++ private fun sizeFor(max: Long): Int = when {+ max <= 0xFF -> 1+ max <= 0xFFFF -> 2+ max <= 0xFFFFFFFFL -> 4+ else -> 8+ }++ private fun writeSized(out: ByteArrayOutputStream, v: Long, size: Int) {+ for (i in size - 1 downTo 0) out.write(((v ushr (8 * i)) and 0xFF).toInt())+ }+ }++ private class Decoder(private val bytes: ByteArray) {+ private var offsetSize = 0+ private var refSize = 0+ private var numObjects = 0L+ private var offsetTableOffset = 0L+ private var depth = 0++ fun decodeRoot(): Any? {+ if (bytes.size < MAGIC.length + TRAILER_SIZE ||+ String(bytes, 0, MAGIC.length, Charsets.US_ASCII) != MAGIC+ ) {+ throw FormatException("not a bplist00")+ }+ val t = bytes.size - TRAILER_SIZE+ offsetSize = bytes[t + 6].toInt() and 0xFF+ refSize = bytes[t + 7].toInt() and 0xFF+ numObjects = readSized(t + 8, 8)+ val top = readSized(t + 16, 8)+ offsetTableOffset = readSized(t + 24, 8)+ if (offsetSize !in 1..8 || refSize !in 1..8 || top >= numObjects ||+ offsetTableOffset + numObjects * offsetSize > t+ ) {+ throw FormatException("corrupt trailer")+ }+ return readObject(top)+ }++ private fun offsetOf(ref: Long): Int {+ if (ref !in 0 until numObjects) throw FormatException("ref $ref out of range")+ val off = readSized((offsetTableOffset + ref * offsetSize).toInt(), offsetSize)+ if (off !in MAGIC.length.toLong() until offsetTableOffset) throw FormatException("bad offset $off")+ return off.toInt()+ }++ private fun readObject(ref: Long): Any? {+ if (++depth > MAX_DEPTH) throw FormatException("nesting too deep")+ try {+ val pos = offsetOf(ref)+ val marker = bytes[pos].toInt() and 0xFF+ val type = marker shr 4+ val info = marker and 0x0F+ return when (type) {+ 0x0 -> when (info) {+ 0x0 -> null+ 0x8 -> false+ 0x9 -> true+ else -> throw FormatException("bad simple marker $marker")+ }+ 0x1 -> readInt(pos + 1, 1 shl info)+ 0x2 -> readReal(pos + 1, 1 shl info)+ 0x3 -> readReal(pos + 1, 8)+ 0x4 -> {+ val (len, start) = countAt(pos, info)+ bytes.copyOfRange(start, checkedEnd(start, len))+ }+ 0x5 -> {+ val (len, start) = countAt(pos, info)+ String(bytes, start, checkedEnd(start, len) - start, Charsets.US_ASCII)+ }+ 0x6 -> {+ val (len, start) = countAt(pos, info)+ String(bytes, start, checkedEnd(start, len * 2) - start, Charsets.UTF_16BE)+ }+ 0x8 -> readSized(pos + 1, info + 1)+ 0xA -> {+ val (count, start) = countAt(pos, info)+ checkedEnd(start, count * refSize)+ List(count) { i -> readObject(readSized(start + i * refSize, refSize)) }+ }+ 0xD -> {+ val (count, start) = countAt(pos, info)+ checkedEnd(start, count * refSize * 2)+ val map = LinkedHashMap<String, Any?>(count)+ for (i in 0 until count) {+ val key = readObject(readSized(start + i * refSize, refSize)) as? String+ ?: throw FormatException("non-string dict key")+ map[key] = readObject(readSized(start + (count + i) * refSize, refSize))+ }+ map+ }+ else -> throw FormatException("unsupported marker $marker")+ }+ } finally {+ depth--+ }+ }++ private fun countAt(pos: Int, info: Int): Pair<Int, Int> {+ if (info != 0x0F) return info to pos + 1+ val intMarker = bytes[pos + 1].toInt() and 0xFF+ if (intMarker shr 4 != 0x1) throw FormatException("bad length marker")+ val size = 1 shl (intMarker and 0x0F)+ val count = readInt(pos + 2, size)+ if (count !in 0..Int.MAX_VALUE.toLong()) throw FormatException("bad length $count")+ return count.toInt() to pos + 2 + size+ }++ private fun checkedEnd(start: Int, len: Int): Int {+ val end = start.toLong() + len+ if (len < 0 || end > offsetTableOffset) throw FormatException("object overruns")+ return end.toInt()+ }++ private fun readInt(pos: Int, size: Int): Long = when (size) {+ 1, 2, 4 -> readSized(pos, size)+ 8 -> readSized(pos, 8)+ 16 -> readSized(pos + 8, 8)+ else -> throw FormatException("bad int size $size")+ }++ private fun readReal(pos: Int, size: Int): Double = when (size) {+ 4 -> ByteBuffer.wrap(bytes, pos, 4).float.toDouble()+ 8 -> ByteBuffer.wrap(bytes, pos, 8).double+ else -> throw FormatException("bad real size $size")+ }++ private fun readSized(pos: Int, size: Int): Long {+ if (pos < 0 || pos + size > bytes.size) throw FormatException("read past end")+ var v = 0L+ for (i in 0 until size) v = (v shl 8) or (bytes[pos + i].toLong() and 0xFF)+ return v+ }+ }++ private const val MAX_DEPTH = 64+}
share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.ktnew file mode 100644index 0000000000..058245b22a--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.kt@@ -0,0 +1,220 @@+package com.vayunmathur.share.domain.airdrop++import java.io.EOFException+import java.io.FilterInputStream+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * cpio archive codec — the `/Upload` body (`application/x-cpio`).+ *+ * Writing produces the portable odc format (`070707`), which is what Apple devices emit and+ * accept. Reading also takes newc (`070701`, and `070702` with an ignored checksum), since+ * Mosey's own reader does.+ */+object Cpio {++ private const val ODC_MAGIC = "070707"+ private const val NEWC_MAGIC = "070701"+ private const val NEWC_CRC_MAGIC = "070702"+ private const val TRAILER = "TRAILER!!!"+ private const val ODC_HEADER_LEN = 76+ private const val NEWC_HEADER_LEN = 110++ const val MODE_DIR = 0x41ED // 040755+ const val MODE_FILE = 0x81A4 // 0100644+ private const val MODE_TYPE_MASK = 0xF000+ private const val MODE_TYPE_DIR = 0x4000+ private const val MODE_TYPE_FILE = 0x8000++ /** Longest name accepted on read; a hostile header must not make us allocate gigabytes. */+ private const val MAX_NAME = 4096++ class FormatException(message: String) : IOException(message)++ /** Streams an odc archive. Close (or [finish]) to write the trailer. */+ class Writer(private val out: OutputStream) : AutoCloseable {+ private var ino = 1L+ private var finished = false++ fun directory(name: String, mtimeSeconds: Long = nowSeconds()) {+ header(name, MODE_DIR, 0, mtimeSeconds)+ }++ /** Writes a file entry whose content is exactly [size] bytes copied from [content]. */+ fun file(name: String, size: Long, content: InputStream, mtimeSeconds: Long = nowSeconds()) {+ header(name, MODE_FILE, size, mtimeSeconds)+ val copied = copyExactly(content, out, size)+ if (copied != size) throw IOException("$name: expected $size bytes, got $copied")+ }++ fun finish() {+ if (finished) return+ finished = true+ header(TRAILER, 0, 0, 0)+ out.flush()+ }++ override fun close() = finish()++ private fun header(name: String, mode: Int, size: Long, mtime: Long) {+ val nameBytes = name.toByteArray(Charsets.UTF_8)+ val sb = StringBuilder(ODC_HEADER_LEN)+ .append(ODC_MAGIC)+ .append(octal(0, 6)) // dev+ .append(octal(if (name == TRAILER) 0 else ino++, 6))+ .append(octal(mode.toLong(), 6))+ .append(octal(0, 6)) // uid+ .append(octal(0, 6)) // gid+ .append(octal(1, 6)) // nlink+ .append(octal(0, 6)) // rdev+ .append(octal(mtime, 11))+ .append(octal(nameBytes.size + 1L, 6))+ .append(octal(size, 11))+ out.write(sb.toString().toByteArray(Charsets.US_ASCII))+ out.write(nameBytes)+ out.write(0)+ }++ private fun octal(v: Long, width: Int): String {+ val s = java.lang.Long.toOctalString(v)+ if (s.length > width) throw IOException("value $v does not fit $width octal digits")+ return s.padStart(width, '0')+ }+ }++ class Entry(+ val name: String,+ val mode: Int,+ val size: Long,+ val mtimeSeconds: Long,+ ) {+ val isDirectory: Boolean get() = mode and MODE_TYPE_MASK == MODE_TYPE_DIR+ val isFile: Boolean get() = mode and MODE_TYPE_MASK == MODE_TYPE_FILE+ }++ /**+ * Pull-style reader. Call [next] for each entry; the returned stream yields exactly that+ * entry's content and is drained automatically by the following [next] call.+ */+ class Reader(private val input: InputStream) {+ private var current: BoundedStream? = null+ private var pad = 0+ private var done = false++ fun next(): Pair<Entry, InputStream>? {+ if (done) return null+ current?.let { it.skipRest(); skipFully(input, pad.toLong()) }+ current = null+ val magic = String(readFully(6), Charsets.US_ASCII)+ val (entry, namePadAfter, dataPad) = when (magic) {+ ODC_MAGIC -> readOdc()+ NEWC_MAGIC, NEWC_CRC_MAGIC -> readNewc()+ else -> throw FormatException("bad cpio magic '$magic'")+ }+ skipFully(input, namePadAfter.toLong())+ if (entry.name == TRAILER) {+ done = true+ return null+ }+ val stream = BoundedStream(input, entry.size)+ current = stream+ pad = dataPad+ return entry to stream+ }++ private fun readOdc(): Triple<Entry, Int, Int> {+ val h = String(readFully(ODC_HEADER_LEN - 6), Charsets.US_ASCII)+ fun field(start: Int, len: Int): Long =+ h.substring(start, start + len).toLongOrNull(8) ?: throw FormatException("bad odc field")+ val mode = field(12, 6).toInt()+ val mtime = field(42, 11)+ val nameSize = field(53, 6).toInt()+ val size = field(59, 11)+ val name = readName(nameSize)+ return Triple(Entry(name, mode, size, mtime), 0, 0)+ }++ private fun readNewc(): Triple<Entry, Int, Int> {+ val h = String(readFully(NEWC_HEADER_LEN - 6), Charsets.US_ASCII)+ fun field(index: Int): Long =+ h.substring(index * 8, index * 8 + 8).toLongOrNull(16) ?: throw FormatException("bad newc field")+ val mode = field(1).toInt()+ val mtime = field(5)+ val size = field(6)+ val nameSize = field(11).toInt()+ val name = readName(nameSize)+ val namePad = align4(NEWC_HEADER_LEN + nameSize)+ return Triple(Entry(name, mode, size, mtime), namePad, align4(size))+ }++ private fun readName(nameSize: Int): String {+ if (nameSize !in 1..MAX_NAME) throw FormatException("bad name size $nameSize")+ val raw = readFully(nameSize)+ return String(raw, 0, nameSize - 1, Charsets.UTF_8)+ }++ private fun readFully(n: Int): ByteArray {+ val buf = ByteArray(n)+ var off = 0+ while (off < n) {+ val r = input.read(buf, off, n - off)+ if (r < 0) throw EOFException("truncated cpio")+ off += r+ }+ return buf+ }+ }++ private class BoundedStream(input: InputStream, private var remaining: Long) : FilterInputStream(input) {+ override fun read(): Int {+ if (remaining <= 0) return -1+ val b = super.read()+ if (b < 0) throw EOFException("truncated cpio entry")+ remaining--+ return b+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (remaining <= 0) return -1+ val r = super.read(b, off, minOf(len.toLong(), remaining).toInt())+ if (r < 0) throw EOFException("truncated cpio entry")+ remaining -= r+ return r+ }++ override fun available(): Int = minOf(super.available().toLong(), remaining).toInt()++ override fun close() = Unit++ fun skipRest() = skipFully(`in`, remaining).also { remaining = 0 }+ }++ private fun align4(n: Long): Int = ((4 - (n % 4)) % 4).toInt()+ private fun align4(n: Int): Int = align4(n.toLong())++ private fun skipFully(input: InputStream, n: Long) {+ var left = n+ val buf = ByteArray(8192)+ while (left > 0) {+ val r = input.read(buf, 0, minOf(left, buf.size.toLong()).toInt())+ if (r < 0) throw EOFException("truncated cpio")+ left -= r+ }+ }++ private fun copyExactly(input: InputStream, out: OutputStream, size: Long): Long {+ val buf = ByteArray(64 * 1024)+ var copied = 0L+ while (copied < size) {+ val r = input.read(buf, 0, minOf(buf.size.toLong(), size - copied).toInt())+ if (r < 0) break+ out.write(buf, 0, r)+ copied += r+ }+ return copied+ }++ private fun nowSeconds(): Long = System.currentTimeMillis() / 1000+}
share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.ktnew file mode 100644index 0000000000..e2f10d473a--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.kt@@ -0,0 +1,174 @@+package com.vayunmathur.share.domain.airdrop++import java.io.EOFException+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream+import java.util.zip.DataFormatException+import java.util.zip.Deflater+import java.util.zip.Inflater++/**+ * `application/x-dvzip` framing — a cpio archive cut into chunks, each sent as a 4-byte+ * big-endian length followed by that many bytes.+ *+ * A length whose top byte is zero marks a zlib-deflated chunk; a non-zero top byte marks a+ * stored chunk whose length is the low 24 bits. A zero length ends the stream. Matches+ * Mosey's `ChunkedInflaterInputStream` (reader) and its 128 KiB per-chunk deflater (writer).+ */+object DvZip {++ const val CHUNK_SIZE = 128 * 1024+ private const val STORED_FLAG = 0x80++ /** Longest chunk accepted on read, compressed or not, so a hostile length cannot OOM us. */+ private const val MAX_CHUNK = 16 * 1024 * 1024++ class Writer(private val out: OutputStream) : OutputStream() {+ private val buffer = ByteArray(CHUNK_SIZE)+ private var filled = 0+ private val deflater = Deflater()+ private val scratch = ByteArray(CHUNK_SIZE + CHUNK_SIZE / 8 + 64)+ private var closed = false++ override fun write(b: Int) {+ if (filled == buffer.size) emit()+ buffer[filled++] = b.toByte()+ }++ override fun write(b: ByteArray, off: Int, len: Int) {+ var o = off+ var left = len+ while (left > 0) {+ if (filled == buffer.size) emit()+ val n = minOf(left, buffer.size - filled)+ System.arraycopy(b, o, buffer, filled, n)+ filled += n+ o += n+ left -= n+ }+ }++ override fun flush() {+ emit()+ out.flush()+ }++ override fun close() {+ if (closed) return+ closed = true+ emit()+ deflater.end()+ out.flush()+ }++ private fun emit() {+ if (filled == 0) return+ deflater.reset()+ deflater.setInput(buffer, 0, filled)+ deflater.finish()+ var len = 0+ while (!deflater.finished()) {+ if (len == scratch.size) throw IOException("deflate output overflow")+ len += deflater.deflate(scratch, len, scratch.size - len)+ }+ writeLength(len)+ out.write(scratch, 0, len)+ filled = 0+ }++ private fun writeLength(len: Int) {+ out.write(len ushr 24 and 0xFF)+ out.write(len ushr 16 and 0xFF)+ out.write(len ushr 8 and 0xFF)+ out.write(len and 0xFF)+ }+ }++ class Reader(private val input: InputStream) : InputStream() {+ private val inflater = Inflater()+ private var chunk = ByteArray(0)+ private var pos = 0+ private var ended = false++ override fun read(): Int {+ if (!fill()) return -1+ return chunk[pos++].toInt() and 0xFF+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (len == 0) return 0+ if (!fill()) return -1+ val n = minOf(len, chunk.size - pos)+ System.arraycopy(chunk, pos, b, off, n)+ pos += n+ return n+ }++ override fun close() {+ inflater.end()+ input.close()+ }++ private fun fill(): Boolean {+ while (pos >= chunk.size) {+ if (ended) return false+ val header = readExactly(4) ?: run { ended = true; return false }+ val stored = (header[0].toInt() and 0xFF) != 0+ if (stored) header[0] = 0+ val len = ((header[0].toInt() and 0xFF) shl 24) or ((header[1].toInt() and 0xFF) shl 16) or+ ((header[2].toInt() and 0xFF) shl 8) or (header[3].toInt() and 0xFF)+ if (len == 0) {+ ended = true+ return false+ }+ if (len > MAX_CHUNK) throw IOException("dvzip chunk too large: $len")+ val body = readExactly(len) ?: throw EOFException("truncated dvzip chunk")+ chunk = if (stored) body else inflate(body)+ pos = 0+ }+ return true+ }++ private fun inflate(body: ByteArray): ByteArray {+ inflater.reset()+ inflater.setInput(body)+ val out = java.io.ByteArrayOutputStream(CHUNK_SIZE)+ val buf = ByteArray(8192)+ try {+ while (!inflater.finished()) {+ val n = inflater.inflate(buf)+ if (n == 0 && inflater.needsInput()) throw IOException("dvzip chunk ends mid-stream")+ out.write(buf, 0, n)+ if (out.size() > MAX_CHUNK) throw IOException("dvzip chunk inflates too large")+ }+ } catch (e: DataFormatException) {+ throw IOException("bad dvzip chunk", e)+ }+ return out.toByteArray()+ }++ /** Null on a clean EOF before the first byte; a truncation after that throws. */+ private fun readExactly(n: Int): ByteArray? {+ val buf = ByteArray(n)+ var off = 0+ while (off < n) {+ val r = input.read(buf, off, n - off)+ if (r < 0) {+ if (off == 0) return null+ throw EOFException("truncated dvzip")+ }+ off += r+ }+ return buf+ }+ }++ /** Stored-chunk length marker, exposed for tests that build a stream by hand. */+ internal fun storedHeader(len: Int): ByteArray = byteArrayOf(+ STORED_FLAG.toByte(),+ (len ushr 16 and 0xFF).toByte(),+ (len ushr 8 and 0xFF).toByte(),+ (len and 0xFF).toByte(),+ )+}
share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.kt b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.ktnew file mode 100644index 0000000000..12a28824fa--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.kt@@ -0,0 +1,124 @@+package com.vayunmathur.share.domain.airdrop++/**+ * Uniform Type Identifiers for AirDrop `Ask` file entries.+ *+ * The extension table and the per-type receiving bundle id are Mosey's own (`cfh`), so an+ * Apple receiver routes each file to the same app it does for a Pixel sender.+ */+object Uti {++ data class Type(val uti: String, val bundleId: String)++ const val FOLDER = "public.folder"+ const val PLAIN_TEXT = "public.plain-text"+ const val LIVE_PHOTO_BUNDLE = "com.apple.private.live-photo-bundle"+ const val NOTES_DOCUMENT = "com.apple.notes.airdrop.document"+ const val DEFAULT_BUNDLE_ID = "com.apple.finder"+ private val DEFAULT = Type("public.data", "com.apple.DocumentsApp")++ private val byExtension: Map<String, Type> = mapOf(+ "pdf" to Type("com.adobe.pdf", "com.apple.Preview"),+ "txt" to Type(PLAIN_TEXT, "com.apple.Notes"),+ "rtf" to Type("public.rtf", "com.apple.TextEdit"),+ "rtfd" to Type("com.apple.rtfd", "com.apple.TextEdit"),+ "html" to Type("public.html", "com.apple.mobilesafari"),+ "htm" to Type("public.html", "com.apple.mobilesafari"),+ "xml" to Type("public.xml", "com.apple.TextEdit"),+ "notesairdropdocument" to Type(NOTES_DOCUMENT, "com.apple.Notes"),+ "epub" to Type("com.apple.epub.document", "com.apple.iBooks"),+ "png" to Type("public.png", "com.apple.mobileslideshow"),+ "jpg" to Type("public.jpeg", "com.apple.mobileslideshow"),+ "jpeg" to Type("public.jpeg", "com.apple.mobileslideshow"),+ "heic" to Type("public.heic", "com.apple.mobileslideshow"),+ "heif" to Type("public.heif", "com.apple.mobileslideshow"),+ "gif" to Type("com.compuserve.gif", "com.apple.mobileslideshow"),+ "tif" to Type("public.tiff", "com.apple.mobileslideshow"),+ "tiff" to Type("public.tiff", "com.apple.mobileslideshow"),+ "dng" to Type("com.adobe.raw-image", "com.apple.mobileslideshow"),+ "raw" to Type("public.camera-raw-image", "com.apple.mobileslideshow"),+ "webp" to Type("org.webmproject.webp", "com.apple.mobileslideshow"),+ "bmp" to Type("com.microsoft.bmp", "com.apple.mobileslideshow"),+ "mp3" to Type("public.mp3", "com.apple.Music"),+ "aiff" to Type("public.aiff-audio", "com.apple.Music"),+ "aif" to Type("public.aiff-audio", "com.apple.Music"),+ "wav" to Type("com.microsoft.waveform-audio", "com.apple.Music"),+ "mid" to Type("public.midi-audio", "com.apple.Music"),+ "midi" to Type("public.midi-audio", "com.apple.Music"),+ "m4a" to Type("public.mpeg-4-audio", "com.apple.Music"),+ "mov" to Type("com.apple.quicktime-movie", "com.apple.TV"),+ "mp4" to Type("public.mpeg-4", "com.apple.TV"),+ "m4v" to Type("public.mpeg-4", "com.apple.TV"),+ "avi" to Type("public.avi", "com.apple.TV"),+ "mpeg" to Type("public.mpeg", "com.apple.TV"),+ "mpg" to Type("public.mpeg", "com.apple.TV"),+ "mkv" to Type("public.matroska-video", "com.apple.DocumentsApp"),+ "pages" to Type("com.apple.iwork.pages.sffpages", "com.apple.iWork.Pages"),+ "numbers" to Type("com.apple.iwork.numbers.sffnumbers", "com.apple.iWork.Numbers"),+ "key" to Type("com.apple.iwork.keynote.sffkey", "com.apple.iWork.Keynote"),+ "usd" to Type("com.pixar.usd", "com.apple.RealityKit.Viewer"),+ "usdz" to Type("com.pixar.usdz", "com.apple.RealityKit.Viewer"),+ "zip" to Type("com.pkware.zip-archive", "com.apple.DocumentsApp"),+ "tar" to Type("public.tar-archive", "com.apple.DocumentsApp"),+ "gz" to Type("org.gnu.gzip-archive", "com.apple.DocumentsApp"),+ "dmg" to Type("com.apple.diskimage", "com.apple.DiskUtility"),+ "ipa" to Type("com.apple.ipa", "com.apple.AppStore"),+ "vcf" to Type("public.vcard", "com.apple.MobileAddressBook"),+ "ics" to Type("public.calendar-event", "com.apple.mobilecal"),+ "url" to Type("public.url", "com.apple.mobilesafari"),+ "webloc" to Type("com.apple.web-location", "com.apple.Safari"),+ "pkpass" to Type("com.apple.pkpass", "com.apple.Passbook"),+ "plist" to Type("com.apple.property-list", "com.apple.TextEdit"),+ "md" to Type("net.daringfireball.markdown", "com.apple.Notes"),+ "csv" to Type("public.comma-separated-values-text", "com.apple.Numbers"),+ )++ private val mimeByUti: Map<String, String> = mapOf(+ "com.adobe.pdf" to "application/pdf",+ "org.idpf.epub-container" to "application/epub+zip",+ "public.zip-archive" to "application/zip",+ "org.gnu.gzip-archive" to "application/gzip",+ NOTES_DOCUMENT to "text/plain",+ "com.apple.rtfd" to "text/rtf",+ "public.html" to "text/html",+ PLAIN_TEXT to "text/plain",+ "public.rtf" to "text/rtf",+ "public.xml" to "text/xml",+ "public.png" to "image/png",+ "public.jpeg" to "image/jpeg",+ "public.heic" to "image/heic",+ "public.heif" to "image/heif",+ "com.compuserve.gif" to "image/gif",+ "public.tiff" to "image/tiff",+ "com.adobe.raw-image" to "image/x-adobe-dng",+ "org.webmproject.webp" to "image/webp",+ "com.microsoft.bmp" to "image/bmp",+ "public.mp3" to "audio/mpeg",+ "public.aiff-audio" to "audio/aiff",+ "com.microsoft.waveform-audio" to "audio/wav",+ "public.midi-audio" to "audio/midi",+ "public.mpeg-4-audio" to "audio/mp4",+ "com.apple.m4a-audio" to "audio/mp4",+ "com.apple.quicktime-movie" to "video/quicktime",+ "public.mpeg-4" to "video/mp4",+ "public.avi" to "video/avi",+ "public.contact" to "text/x-vcard",+ "public.vcard" to "text/x-vcard",+ )++ /** Extension Mosey's receiver substitutes for a live-photo bundle's still image. */+ private val extensionBySubType: Map<String, String> = mapOf(+ "public.heic" to "heic",+ "public.jpeg" to "jpg",+ "com.adobe.raw-image" to "dng",+ "public.png" to "png",+ )++ fun forFileName(name: String): Type =+ byExtension[name.substringAfterLast('.', "").lowercase()] ?: DEFAULT++ /** MIME type for a received file, or null when the UTI says nothing useful. */+ fun mimeTypeOf(uti: String?): String? = uti?.let { mimeByUti[it] }++ fun extensionForSubType(subType: String?): String? = subType?.let { extensionBySubType[it] }+}
share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.kt b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.ktnew file mode 100644index 0000000000..f6885fe093--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.kt@@ -0,0 +1,235 @@+package com.vayunmathur.share.network.airdrop++import java.io.ByteArrayOutputStream+import java.io.EOFException+import java.io.FilterInputStream+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream+import java.util.zip.GZIPInputStream+import java.util.zip.InflaterInputStream++/**+ * Just enough HTTP/1.1 for AirDrop: `POST` with a `Content-Length` or chunked body, and+ * keep-alive between `/Discover`, `/Ask` and `/Upload` on one connection.+ *+ * Hand-rolled rather than OkHttp because the server half is needed too, and both halves have+ * to run over sockets bound to a specific network (`mosey0` or Wi-Fi).+ */+object AirDropHttp {++ private const val MAX_LINE = 8192+ private const val MAX_HEADERS = 100++ /** Largest plist body read into memory; `/Upload` is the only big body and is streamed. */+ const val MAX_PLIST_BODY = 4 * 1024 * 1024++ class ProtocolException(message: String) : IOException(message)++ /** Header names are stored lowercased; HTTP header names are case-insensitive. */+ class Headers(private val map: Map<String, String>) {+ operator fun get(name: String): String? = map[name.lowercase()]+ val contentLength: Long? get() = this["content-length"]?.trim()?.toLongOrNull()+ val isChunked: Boolean get() = this["transfer-encoding"]?.contains("chunked", ignoreCase = true) == true+ val keepAlive: Boolean get() = this["connection"]?.equals("close", ignoreCase = true) != true+ override fun toString(): String = map.toString()+ }++ class Request(val method: String, val path: String, val headers: Headers, val body: InputStream) {+ fun readBody(limit: Int = MAX_PLIST_BODY): ByteArray = readLimited(body, limit)+ }++ class Response(+ val status: Int,+ val headers: Map<String, String> = emptyMap(),+ val body: ByteArray = ByteArray(0),+ ) {+ val isSuccessful: Boolean get() = status in 200..299+ }++ fun readRequest(input: InputStream): Request? {+ val line = readLine(input) ?: return null+ val parts = line.split(' ')+ if (parts.size < 3) throw ProtocolException("bad request line: $line")+ val headers = readHeaders(input)+ return Request(parts[0], parts[1].substringBefore('?'), headers, bodyStream(input, headers, requestBody = true))+ }++ fun readResponse(input: InputStream, limit: Int = MAX_PLIST_BODY): Response {+ val line = readLine(input) ?: throw EOFException("connection closed before response")+ val status = line.split(' ').getOrNull(1)?.toIntOrNull() ?: throw ProtocolException("bad status line: $line")+ val headers = readHeaders(input)+ val raw = bodyStream(input, headers, requestBody = false)+ val decoded = when (headers["content-encoding"]?.lowercase()?.trim()) {+ "gzip" -> GZIPInputStream(raw)+ "deflate" -> InflaterInputStream(raw)+ else -> raw+ }+ return Response(status, emptyMap(), readLimited(decoded, limit))+ }++ fun writeRequestHead(out: OutputStream, method: String, path: String, headers: List<Pair<String, String>>) {+ val sb = StringBuilder("$method $path HTTP/1.1\r\n")+ headers.forEach { (k, v) -> sb.append(k).append(": ").append(v).append("\r\n") }+ sb.append("\r\n")+ out.write(sb.toString().toByteArray(Charsets.ISO_8859_1))+ }++ fun writeResponse(out: OutputStream, response: Response, keepAlive: Boolean) {+ val sb = StringBuilder("HTTP/1.1 ${response.status} ${reason(response.status)}\r\n")+ response.headers.forEach { (k, v) -> sb.append(k).append(": ").append(v).append("\r\n") }+ sb.append("Content-Length: ").append(response.body.size).append("\r\n")+ sb.append("Connection: ").append(if (keepAlive) "keep-alive" else "close").append("\r\n\r\n")+ out.write(sb.toString().toByteArray(Charsets.ISO_8859_1))+ out.write(response.body)+ out.flush()+ }++ /** Wraps [out] so writes become HTTP chunks; [ChunkedOutputStream.finish] writes the terminator. */+ class ChunkedOutputStream(private val out: OutputStream) : OutputStream() {+ private var finished = false++ override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)++ override fun write(b: ByteArray, off: Int, len: Int) {+ if (len == 0) return+ out.write("${Integer.toHexString(len)}\r\n".toByteArray(Charsets.US_ASCII))+ out.write(b, off, len)+ out.write(CRLF)+ }++ override fun flush() = out.flush()++ fun finish() {+ if (finished) return+ finished = true+ out.write("0\r\n\r\n".toByteArray(Charsets.US_ASCII))+ out.flush()+ }++ /** Finishes but leaves the socket open for the response. */+ override fun close() = finish()+ }++ private val CRLF = byteArrayOf('\r'.code.toByte(), '\n'.code.toByte())++ private fun bodyStream(input: InputStream, headers: Headers, requestBody: Boolean): InputStream = when {+ headers.isChunked -> ChunkedInputStream(input)+ headers.contentLength != null -> BoundedInputStream(input, headers.contentLength!!)+ // A request with neither has no body; a response with neither runs to close.+ requestBody -> BoundedInputStream(input, 0)+ else -> NonClosingInputStream(input)+ }++ private fun readHeaders(input: InputStream): Headers {+ val map = LinkedHashMap<String, String>()+ repeat(MAX_HEADERS) {+ val line = readLine(input) ?: throw EOFException("headers truncated")+ if (line.isEmpty()) return Headers(map)+ val colon = line.indexOf(':')+ if (colon > 0) map[line.substring(0, colon).trim().lowercase()] = line.substring(colon + 1).trim()+ }+ throw ProtocolException("too many headers")+ }++ /** One CRLF- (or LF-) terminated line, or null at a clean EOF before any byte. */+ private fun readLine(input: InputStream): String? {+ val out = ByteArrayOutputStream()+ while (true) {+ val b = input.read()+ if (b < 0) {+ if (out.size() == 0) return null+ throw EOFException("line truncated")+ }+ if (b == '\n'.code) break+ if (out.size() >= MAX_LINE) throw ProtocolException("line too long")+ out.write(b)+ }+ val bytes = out.toByteArray()+ val len = if (bytes.isNotEmpty() && bytes.last() == '\r'.code.toByte()) bytes.size - 1 else bytes.size+ return String(bytes, 0, len, Charsets.ISO_8859_1)+ }++ fun readLimited(input: InputStream, limit: Int): ByteArray {+ val out = ByteArrayOutputStream()+ val buf = ByteArray(8192)+ while (true) {+ val n = input.read(buf)+ if (n < 0) break+ if (out.size() + n > limit) throw ProtocolException("body exceeds $limit bytes")+ out.write(buf, 0, n)+ }+ return out.toByteArray()+ }++ /** Reads and discards whatever is left, so the next request on the connection lines up. */+ fun drain(input: InputStream) {+ val buf = ByteArray(8192)+ while (input.read(buf) >= 0) Unit+ }++ private fun reason(status: Int): String = when (status) {+ 200 -> "OK"+ 400 -> "Bad Request"+ 401 -> "Unauthorized"+ 404 -> "Not Found"+ 500 -> "Internal Server Error"+ else -> "Status"+ }++ private class NonClosingInputStream(input: InputStream) : FilterInputStream(input) {+ override fun close() = Unit+ }++ private class BoundedInputStream(input: InputStream, private var remaining: Long) : FilterInputStream(input) {+ override fun read(): Int {+ if (remaining <= 0) return -1+ val b = super.read()+ if (b < 0) throw EOFException("body truncated")+ remaining--+ return b+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (remaining <= 0) return -1+ val n = super.read(b, off, minOf(len.toLong(), remaining).toInt())+ if (n < 0) throw EOFException("body truncated")+ remaining -= n+ return n+ }++ override fun close() = Unit+ }++ private class ChunkedInputStream(input: InputStream) : FilterInputStream(input) {+ private var chunkLeft = 0L+ private var done = false++ override fun read(): Int {+ val one = ByteArray(1)+ return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xFF+ }++ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (done) return -1+ if (chunkLeft == 0L) {+ val sizeLine = readLine(`in`) ?: throw EOFException("chunked body truncated")+ chunkLeft = sizeLine.substringBefore(';').trim().toLongOrNull(16)+ ?: throw ProtocolException("bad chunk size '$sizeLine'")+ if (chunkLeft == 0L) {+ // Trailers, if any, end with an empty line.+ while (!readLine(`in`).isNullOrEmpty()) Unit+ done = true+ return -1+ }+ }+ val n = `in`.read(b, off, minOf(len.toLong(), chunkLeft).toInt())+ if (n < 0) throw EOFException("chunk truncated")+ chunkLeft -= n+ if (chunkLeft == 0L) readLine(`in`)+ return n+ }++ override fun close() = Unit+ }+}
share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.kt b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.ktnew file mode 100644index 0000000000..985839fddb--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.kt@@ -0,0 +1,107 @@+package com.vayunmathur.share.network.airdrop++import com.vayunmathur.share.domain.airdrop.AirDropMessages+import java.io.BufferedInputStream+import java.io.BufferedOutputStream+import java.io.OutputStream+import java.net.Inet6Address+import java.net.InetAddress+import java.net.InetSocketAddress+import java.net.Socket+import javax.net.SocketFactory+import javax.net.ssl.SSLSocket+import javax.net.ssl.SSLSocketFactory++private const val CONNECT_TIMEOUT_MS = 5_000++/**+ * One HTTPS connection to an AirDrop receiver, reused for Discover → Ask → Upload.+ *+ * [socketFactory] comes from the selected link, so traffic is pinned to `mosey0` when the+ * peer was found there rather than leaking out over Wi-Fi.+ */+class AirDropHttpClient(+ private val address: InetAddress,+ private val port: Int,+ private val socketFactory: SocketFactory,+ private val readTimeoutMs: Int,+) : AutoCloseable {++ private val tls: SSLSocketFactory = AirDropTls.clientContext().socketFactory+ private var socket: SSLSocket? = null+ private var input: BufferedInputStream? = null+ private var output: BufferedOutputStream? = null++ /** `Host` exactly as Mosey writes it, with IPv6 bracketed (`cce.z`). */+ private val hostHeader: String+ get() {+ val host = (address as? Inet6Address)?.let { "[${it.hostAddress?.substringBefore('%')}]" } ?: address.hostAddress+ return "$host:$port"+ }++ private fun connection(): Pair<BufferedInputStream, BufferedOutputStream> {+ val existing = socket+ if (existing != null && !existing.isClosed) return input!! to output!!+ val raw: Socket = socketFactory.createSocket()+ raw.connect(InetSocketAddress(address, port), CONNECT_TIMEOUT_MS)+ val ssl = tls.createSocket(raw, address.hostAddress, port, true) as SSLSocket+ ssl.enabledProtocols = AirDropTls.PROTOCOLS.filter { it in ssl.supportedProtocols }.toTypedArray()+ ssl.soTimeout = readTimeoutMs+ ssl.startHandshake()+ socket = ssl+ input = BufferedInputStream(ssl.inputStream)+ output = BufferedOutputStream(ssl.outputStream)+ return input!! to output!!+ }++ fun postPlist(path: String, body: ByteArray, keepAlive: Boolean = true): AirDropHttp.Response {+ val (inp, out) = connection()+ AirDropHttp.writeRequestHead(+ out,+ "POST",+ path,+ listOf(+ "Host" to hostHeader,+ "Content-Type" to AirDropMessages.CONTENT_TYPE_PLIST,+ "Connection" to if (keepAlive) "keep-alive" else "close",+ "Accept" to "*/*",+ "User-Agent" to AirDropMessages.USER_AGENT,+ "Accept-Language" to "en-us",+ "Accept-Encoding" to "gzip, deflate",+ "Content-Length" to body.size.toString(),+ ),+ )+ out.write(body)+ out.flush()+ val response = AirDropHttp.readResponse(inp)+ if (!keepAlive) close()+ return response+ }++ /** Streams an `/Upload` body through [writeBody] using chunked transfer encoding. */+ fun upload(contentType: String, totalBytes: Long, transferId: String?, writeBody: (OutputStream) -> Unit): AirDropHttp.Response {+ val (inp, out) = connection()+ val headers = buildList {+ add("Host" to hostHeader)+ add("Content-Type" to contentType)+ add("Connection" to "keep-alive")+ add("User-Agent" to AirDropMessages.USER_AGENT)+ add("TotalBytes" to totalBytes.toString())+ add("Transfer-Encoding" to "chunked")+ add("Accept-Encoding" to "identity")+ transferId?.let { add("TransferID" to it) }+ }+ AirDropHttp.writeRequestHead(out, "POST", "/Upload", headers)+ val chunked = AirDropHttp.ChunkedOutputStream(out)+ writeBody(chunked)+ chunked.finish()+ return AirDropHttp.readResponse(inp)+ }++ override fun close() {+ runCatching { socket?.close() }+ socket = null+ input = null+ output = null+ }+}
share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.kt b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.ktnew file mode 100644index 0000000000..13675f3af9--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.kt@@ -0,0 +1,105 @@+package com.vayunmathur.share.network.airdrop++import com.vayunmathur.library.log.Log+import java.net.InetAddress+import java.net.InetSocketAddress+import java.net.SocketException+import javax.net.ssl.SSLServerSocket+import javax.net.ssl.SSLSocket+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch++private const val TAG = "AirDropHttpServer"+private const val CLIENT_TIMEOUT_MS = 120_000++/**+ * The receiver's HTTPS endpoint, listening on `[::]` so it answers on whichever link the+ * sender reached us over (`mosey0` link-local or the Wi-Fi LAN).+ *+ * Each connection is served on its own coroutine and may carry several requests in a row;+ * `/Ask` can suspend for as long as the user takes to answer.+ */+class AirDropHttpServer(private val handler: Handler) {++ fun interface Handler {+ suspend fun handle(request: AirDropHttp.Request, remote: InetAddress): AirDropHttp.Response+ }++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var server: SSLServerSocket? = null+ private var acceptJob: Job? = null++ val port: Int? get() = server?.localPort++ /** Binds a fresh TLS identity on an ephemeral port and returns it. Idempotent. */+ @Synchronized+ fun start(): Int {+ server?.let { return it.localPort }+ val socket = AirDropTls.serverContext().serverSocketFactory.createServerSocket() as SSLServerSocket+ socket.reuseAddress = true+ socket.bind(InetSocketAddress(InetAddress.getByName("::"), 0))+ socket.enabledProtocols = AirDropTls.PROTOCOLS.filter { it in socket.supportedProtocols }.toTypedArray()+ server = socket+ acceptJob = scope.launch { acceptLoop(socket) }+ Log.status(TAG, "listening on port ${socket.localPort}")+ return socket.localPort+ }++ @Synchronized+ fun stop() {+ acceptJob?.cancel()+ acceptJob = null+ runCatching { server?.close() }+ server = null+ }++ fun release() {+ stop()+ scope.cancel()+ }++ // Broad catch is deliberate: the accept loop must outlive undocumented RuntimeExceptions+ // from the TLS stack, and only stop when the socket is closed.+ @Suppress("TooGenericExceptionCaught")+ private suspend fun acceptLoop(socket: SSLServerSocket) {+ while (scope.isActive && !socket.isClosed) {+ try {+ val client = socket.accept() as SSLSocket+ client.soTimeout = CLIENT_TIMEOUT_MS+ scope.launch { serve(client) }+ } catch (e: SocketException) {+ if (!socket.isClosed) Log.status(TAG, "accept failed", e)+ } catch (e: Exception) {+ Log.status(TAG, "accept failed", e)+ }+ }+ }++ // Broad catch is deliberate: a misbehaving peer must cost one connection, not the server.+ @Suppress("TooGenericExceptionCaught")+ private suspend fun serve(client: SSLSocket) {+ val remote = client.inetAddress+ try {+ client.use {+ val input = client.inputStream.buffered()+ val output = client.outputStream.buffered()+ while (true) {+ val request = AirDropHttp.readRequest(input) ?: break+ Log.dev(TAG, "${request.method} ${request.path} from ${remote.hostAddress}")+ val response = handler.handle(request, remote)+ AirDropHttp.drain(request.body)+ val keepAlive = request.headers.keepAlive+ AirDropHttp.writeResponse(output, response, keepAlive)+ if (!keepAlive) break+ }+ }+ } catch (e: Exception) {+ Log.status(TAG, "connection from ${remote?.hostAddress} ended", e)+ }+ }+}
share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.kt
diff --git a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.kt b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.ktnew file mode 100644index 0000000000..a0b958c0b7--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.kt@@ -0,0 +1,143 @@+package com.vayunmathur.share.network.airdrop++import android.annotation.SuppressLint+import java.io.ByteArrayOutputStream+import java.math.BigInteger+import java.net.Socket+import java.security.KeyPair+import java.security.KeyPairGenerator+import java.security.KeyStore+import java.security.SecureRandom+import java.security.Signature+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import java.util.TimeZone+import javax.net.ssl.KeyManagerFactory+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLEngine+import javax.net.ssl.X509ExtendedTrustManager++/**+ * TLS for AirDrop's HTTPS.+ *+ * AirDrop in "Everyone" mode authenticates nobody at the TLS layer: Mosey's server presents a+ * fresh self-signed RSA-2048 certificate and its client trusts any certificate (`cea`, `cev`).+ * Apple peers do the same with their own self-signed identities, so the trust-all client here+ * is the protocol, not a shortcut — sender identity is what the user approves in the Ask.+ */+object AirDropTls {++ private const val VALIDITY_MS = 365L * 24 * 60 * 60 * 1000+ private const val BACKDATE_MS = 60L * 60 * 1000+ private const val KEY_ALIAS = "selfsigned"+ val PROTOCOLS = arrayOf("TLSv1.3", "TLSv1.2")++ /** Server context with a newly minted self-signed identity. */+ fun serverContext(commonName: String = "AirDrop"): SSLContext {+ val keyPair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair()+ val cert = selfSignedCertificate(keyPair, commonName)+ val password = CharArray(0)+ val ks = KeyStore.getInstance(KeyStore.getDefaultType()).apply {+ load(null, null)+ setKeyEntry(KEY_ALIAS, keyPair.private, password, arrayOf(cert))+ }+ val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(ks, password) }+ return SSLContext.getInstance("TLS").apply { init(kmf.keyManagers, null, SecureRandom()) }+ }++ fun clientContext(): SSLContext =+ SSLContext.getInstance("TLS").apply { init(null, arrayOf(TrustAll), SecureRandom()) }++ /** Accepts any peer certificate; see the object doc for why that is the protocol. */+ @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager")+ private object TrustAll : X509ExtendedTrustManager() {+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?, socket: Socket?) = Unit+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?, socket: Socket?) = Unit+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?, engine: SSLEngine?) = Unit+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?, engine: SSLEngine?) = Unit+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()+ }++ /** A minimal X.509 v3 certificate, DER-encoded by hand and signed SHA256withRSA. */+ fun selfSignedCertificate(keyPair: KeyPair, commonName: String, now: Long = System.currentTimeMillis()): X509Certificate {+ val sigAlg = Der.seq(Der.oid(SHA256_WITH_RSA), Der.NULL)+ val name = Der.seq(Der.set(Der.seq(Der.oid(COMMON_NAME), Der.utf8(commonName))))+ val tbs = Der.seq(+ Der.explicit(0, Der.int(BigInteger.valueOf(2))),+ Der.int(BigInteger(127, SecureRandom()).add(BigInteger.ONE)),+ sigAlg,+ name,+ Der.seq(Der.utcTime(now - BACKDATE_MS), Der.utcTime(now + VALIDITY_MS)),+ name,+ keyPair.public.encoded,+ )+ val signature = Signature.getInstance("SHA256withRSA").run {+ initSign(keyPair.private)+ update(tbs)+ sign()+ }+ val der = Der.seq(tbs, sigAlg, Der.bitString(signature))+ return CertificateFactory.getInstance("X.509").generateCertificate(der.inputStream()) as X509Certificate+ }++ private val SHA256_WITH_RSA = intArrayOf(1, 2, 840, 113549, 1, 1, 11)+ private val COMMON_NAME = intArrayOf(2, 5, 4, 3)++ private object Der {+ val NULL = byteArrayOf(0x05, 0x00)++ fun seq(vararg parts: ByteArray) = tlv(0x30, concat(parts))+ fun set(vararg parts: ByteArray) = tlv(0x31, concat(parts))+ fun explicit(tag: Int, inner: ByteArray) = tlv(0xA0 or tag, inner)+ fun int(v: BigInteger) = tlv(0x02, v.toByteArray())+ fun utf8(s: String) = tlv(0x0C, s.toByteArray(Charsets.UTF_8))+ fun bitString(bytes: ByteArray) = tlv(0x03, byteArrayOf(0) + bytes)++ fun utcTime(millis: Long): ByteArray {+ val fmt = SimpleDateFormat("yyMMddHHmmss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }+ return tlv(0x17, fmt.format(Date(millis)).toByteArray(Charsets.US_ASCII))+ }++ fun oid(arcs: IntArray): ByteArray {+ val out = ByteArrayOutputStream()+ out.write(arcs[0] * 40 + arcs[1])+ for (arc in arcs.drop(2)) {+ val stack = ArrayDeque<Int>()+ var v = arc+ stack.addFirst(v and 0x7F)+ v = v ushr 7+ while (v > 0) {+ stack.addFirst((v and 0x7F) or 0x80)+ v = v ushr 7+ }+ stack.forEach(out::write)+ }+ return tlv(0x06, out.toByteArray())+ }++ private fun tlv(tag: Int, value: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ out.write(tag)+ val len = value.size+ when {+ len < 0x80 -> out.write(len)+ len <= 0xFF -> { out.write(0x81); out.write(len) }+ len <= 0xFFFF -> { out.write(0x82); out.write(len ushr 8); out.write(len and 0xFF) }+ else -> { out.write(0x83); out.write(len ushr 16); out.write(len ushr 8 and 0xFF); out.write(len and 0xFF) }+ }+ out.write(value)+ return out.toByteArray()+ }++ private fun concat(parts: Array<out ByteArray>): ByteArray {+ val out = ByteArrayOutputStream()+ parts.forEach(out::write)+ return out.toByteArray()+ }+ }+}
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 92e8006700..3a8ebae461 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,6 +4,7 @@ import com.vayunmathur.library.log.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.IncomingTransfer import com.vayunmathur.share.platform.ReceivedFile import com.vayunmathur.share.platform.ReceivedFileStore import java.io.File@@ -600,8 +601,8 @@ class Connection( val session: ShareSession, val incoming: Boolean, val remoteEndpoint: String,-) {- val sessionHandle: Long get() = session.handle+) : IncomingTransfer {+ override val sessionHandle: Long get() = session.handle /** Serialises every write to [socket]; see `TcpTransport.drainAll`. */ internal val writeLock = Any()@@ -610,8 +611,8 @@ class Connection( internal val introductionSent = java.util.concurrent.atomic.AtomicBoolean(false) var pumpJob: Job? = null- val state: MutableStateFlow<ShareState> = MutableStateFlow(ShareState.Handshaking)- val pendingFiles: MutableStateFlow<List<PendingFile>> = MutableStateFlow(emptyList())+ override val state: MutableStateFlow<ShareState> = MutableStateFlow(ShareState.Handshaking)+ override val pendingFiles: MutableStateFlow<List<PendingFile>> = MutableStateFlow(emptyList()) /** The peer's advertised device name, once its `CONNECTION_REQUEST` has been read. */ val peerName: MutableStateFlow<String?> = MutableStateFlow(null)@@ -622,18 +623,18 @@ class Connection( * Announced by the peer's `INTRODUCTION` when receiving and by our own when sending, so * a percentage is computable without the caller summing file sizes itself. */- val expectedTotalBytes: MutableStateFlow<Long> = MutableStateFlow(0L)+ override val expectedTotalBytes: MutableStateFlow<Long> = MutableStateFlow(0L) /** Files that finished arriving, each staged in app-private storage. */- val receivedFiles: MutableStateFlow<List<ReceivedFile>> = MutableStateFlow(emptyList())+ override val receivedFiles: MutableStateFlow<List<ReceivedFile>> = MutableStateFlow(emptyList()) val bytesSent: MutableStateFlow<Long> = MutableStateFlow(0L) /** Decrypted payload bytes received, comparable to [expectedTotalBytes]. */- val bytesReceived: MutableStateFlow<Long> = MutableStateFlow(0L)- val error: MutableStateFlow<String?> = MutableStateFlow(null)+ override val bytesReceived: MutableStateFlow<Long> = MutableStateFlow(0L)+ override val error: MutableStateFlow<String?> = MutableStateFlow(null) /** A name to show a human: the peer's own, falling back to its address. */- val displayName: String get() = peerName.value ?: remoteEndpoint+ override val displayName: String get() = peerName.value ?: remoteEndpoint } /** No further frames will flow: the pump can stop and a terminal notification is due. */
share/src/main/java/com/vayunmathur/share/platform/IncomingTransfer.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/IncomingTransfer.kt b/share/src/main/java/com/vayunmathur/share/platform/IncomingTransfer.ktnew file mode 100644index 0000000000..57484aaebe--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/IncomingTransfer.kt@@ -0,0 +1,23 @@+package com.vayunmathur.share.platform++import com.vayunmathur.share.domain.protocol.PendingFile+import com.vayunmathur.share.domain.protocol.ShareState+import kotlinx.coroutines.flow.StateFlow++/**+ * What the receive notifications need from an incoming transfer, whichever protocol carried it:+ * a Quick Share [com.vayunmathur.share.network.transport.Connection] or an AirDrop session.+ *+ * [sessionHandle] is the identity a notification action carries. Quick Share handles are+ * native pointers (positive); AirDrop handles are negative, so the two never collide.+ */+interface IncomingTransfer {+ val sessionHandle: Long+ val state: StateFlow<ShareState>+ val pendingFiles: StateFlow<List<PendingFile>>+ val receivedFiles: StateFlow<List<ReceivedFile>>+ val bytesReceived: StateFlow<Long>+ val expectedTotalBytes: StateFlow<Long>+ val error: StateFlow<String?>+ val displayName: String+}
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.ktindex 11a40f36df..b7d183ed52 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt@@ -63,6 +63,16 @@ class ReceivedFileStore(private val context: Context) { } } + /**+ * A fresh, uniquely named file in the staging directory for a whole-file writer such as+ * the AirDrop archive extractor. [name] is reduced to its last path component.+ */+ fun newFile(name: String): File {+ dir.mkdirs()+ val safeName = name.substringAfterLast('/').substringAfterLast('\\').ifBlank { "received_file" }+ return synchronized(lock) { uniqueFile(dir, safeName).also { it.createNewFile() } }+ }+ /** * Abandon any streams still open for [sessionKey], e.g. on disconnect. *
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 bf8a6843db..08e5091074 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -13,6 +13,7 @@ import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.AppMessages import com.vayunmathur.share.R+import com.vayunmathur.share.platform.airdrop.AirDropSender import com.vayunmathur.share.platform.discovery.DiscoverySource import com.vayunmathur.share.platform.discovery.NearbyDevice import com.vayunmathur.share.platform.receive.ShareReceiveController@@ -54,6 +55,7 @@ class ShareViewModel( private val nsd get() = ShareReceiveController.nsd(appContext) private val ble get() = ShareReceiveController.ble(appContext) private val transport get() = ShareReceiveController.transport(appContext)+ private val airDrop get() = ShareReceiveController.airDrop(appContext) val localName: String get() = ShareReceiveController.localName @@ -95,6 +97,7 @@ class ShareViewModel( private var scanNsdJob: Job? = null private var scanBleJob: Job? = null+ private var scanAirDropJob: Job? = null // Broad catches are deliberate: discovery flows and the transport throw // undocumented RuntimeExceptions (not just IOException), which read as@@ -125,6 +128,16 @@ class ShareViewModel( Log.status(TAG, "BLE scan error", e) } }+ scanAirDropJob = viewModelScope.launch {+ try {+ // _airdrop._tcp over Mosey's AWDL link when the HAL exists, else over Wi-Fi.+ airDrop.browse().collect { dev ->+ _discoveredDevices.value = mergeDevice(_discoveredDevices.value, dev)+ }+ } catch (e: Exception) {+ Log.status(TAG, "AirDrop browse error", e)+ }+ } } private fun mergeDevice(current: List<NearbyDevice>, incoming: NearbyDevice): List<NearbyDevice> {@@ -156,8 +169,10 @@ class ShareViewModel( override fun stopScan() { scanNsdJob?.cancel() scanBleJob?.cancel()+ scanAirDropJob?.cancel() scanNsdJob = null scanBleJob = null+ scanAirDropJob = null nsd.stopDiscovery() ble.stopScan() _isScanning.value = false@@ -165,6 +180,10 @@ class ShareViewModel( @Suppress("TooGenericExceptionCaught") override fun connectToDevice(device: NearbyDevice) {+ if (device.source == DiscoverySource.AirDrop) {+ sendViaAirDrop(device)+ return+ } val host = device.host val port = device.port if (host == null || port == null) {@@ -248,6 +267,39 @@ class ShareViewModel( } } + /**+ * AirDrop has no long-lived session to show, so the outcome is reported as a message: Ask,+ * then a single Upload, then done.+ */+ private fun sendViaAirDrop(device: NearbyDevice) {+ val uris = _outgoingUris.value+ if (uris.isEmpty()) {+ AppMessages.show(appContext.getString(R.string.share_nothing_selected))+ return+ }+ if (!connecting.compareAndSet(false, true)) return+ stopScan()+ viewModelScope.launch {+ val files = withContext(Dispatchers.IO) { uris.mapNotNull { uriToTempFile(appContext, it) } }+ try {+ if (files.isEmpty()) return@launch+ ShareTransferService.startSendMode(appContext)+ AppMessages.show(appContext.getString(R.string.share_airdrop_waiting, device.endpointName))+ val result = airDrop.send(device, files) { _, _ -> }+ val message = when (result) {+ AirDropSender.Result.Sent -> appContext.getString(R.string.share_airdrop_sent, device.endpointName)+ AirDropSender.Result.Declined -> appContext.getString(R.string.share_airdrop_declined, device.endpointName)+ is AirDropSender.Result.Failed -> appContext.getString(R.string.share_airdrop_failed, result.reason)+ }+ AppMessages.show(message)+ } finally {+ files.forEach { it.delete() }+ ShareTransferService.stop(appContext)+ connecting.set(false)+ }+ }+ }+ private suspend fun sendUrisOver(conn: Connection, uris: List<Uri>) = withContext(Dispatchers.IO) { val files = uris.mapNotNull { uri -> uriToTempFile(appContext, uri) } if (files.isEmpty()) return@withContext
share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.ktnew file mode 100644index 0000000000..f5448de7d8--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.kt@@ -0,0 +1,143 @@+package com.vayunmathur.share.platform.airdrop++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.share.domain.airdrop.AirDropMessages+import com.vayunmathur.share.network.airdrop.AirDropHttpServer+import com.vayunmathur.share.platform.ReceivedFileStore+import com.vayunmathur.share.platform.airdrop.link.AirDropLink+import com.vayunmathur.share.platform.airdrop.link.AirDropLinkSelector+import com.vayunmathur.share.platform.airdrop.link.MoseyStatus+import com.vayunmathur.share.platform.discovery.DiscoverySource+import com.vayunmathur.share.platform.discovery.NearbyDevice+import java.io.File+import java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.emitAll+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.mapNotNull+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++private const val TAG = "AirDrop"++/**+ * Owns AirDrop for the process: the selected link (Mosey or Wi-Fi), the HTTPS receiver, the+ * mDNS records, and the sender.+ *+ * The link is reference-counted across receiving, browsing and sending, because bringing up+ * Mosey starts an AWDL radio session that should run only while something needs it.+ */+class AirDropController(+ context: Context,+ store: ReceivedFileStore,+ private val localName: () -> String,+) {+ private val app = context.applicationContext+ private val discovery = AirDropDiscovery(app)+ private val ble = AirDropBleAdvertiser(app)+ private val sender = AirDropSender(localName)++ val receiver = AirDropReceiver(+ store = store,+ localName = localName,+ freeBytes = { app.filesDir.usableSpace },+ onTransfer = { remote, started ->+ val link = selection?.link ?: return@AirDropReceiver+ if (started) link.onTransferStarted(remote) else link.onTransferEnded(remote)+ },+ )+ private val server = AirDropHttpServer(receiver::handle)++ private val linkLock = Mutex()+ private var selection: AirDropLinkSelector.Selection? = null+ private var users = 0+ private var receiving = false++ private val _mosey = MutableStateFlow<MoseyStatus?>(null)++ /** What Mosey detection found the last time a link was selected; null before that. */+ val mosey: StateFlow<MoseyStatus?> = _mosey.asStateFlow()++ /** Peers listed by the last browse, keyed by the [NearbyDevice.endpointId] shown for them. */+ private val peers = ConcurrentHashMap<String, AirDropPeer>()++ private suspend fun acquire(): AirDropLink = linkLock.withLock {+ val current = selection ?: AirDropLinkSelector.select(app).also {+ selection = it+ _mosey.value = it.mosey+ Log.status(TAG, "link: ${it.link.kind}")+ }+ users+++ current.link+ }++ private suspend fun release() = linkLock.withLock {+ users = (users - 1).coerceAtLeast(0)+ if (users == 0) {+ selection?.link?.deactivate()+ selection = null+ }+ }++ suspend fun startReceiving() {+ if (receiving) return+ receiving = true+ val link = acquire()+ val port = server.start()+ discovery.advertise(AirDropMessages.randomShortId(), port, link.network)+ }++ suspend fun stopReceiving() {+ if (!receiving) return+ receiving = false+ discovery.unadvertise()+ server.stop()+ release()+ }++ /** Lists AirDrop receivers with their names while collected. */+ fun browse(): Flow<NearbyDevice> = flow {+ val link = acquire()+ ble.start()+ try {+ emitAll(+ discovery.browse(link.network).mapNotNull { peer ->+ val info = sender.discover(peer, link) ?: return@mapNotNull null+ val id = "airdrop:${peer.serviceName}"+ peers[id] = peer+ NearbyDevice(+ endpointId = id,+ endpointName = info.receiverComputerName,+ serviceName = peer.serviceName,+ host = peer.address.hostAddress,+ port = peer.port,+ source = DiscoverySource.AirDrop,+ )+ },+ )+ } finally {+ ble.stop()+ release()+ }+ }++ suspend fun send(device: NearbyDevice, files: List<File>, onProgress: (Long, Long) -> Unit): AirDropSender.Result {+ val peer = peers[device.endpointId] ?: return AirDropSender.Result.Failed("receiver is no longer listed")+ val link = acquire()+ return try {+ sender.send(peer, link, files, onProgress)+ } finally {+ release()+ }+ }++ fun accept(handle: Long, accept: Boolean): Int = receiver.accept(handle, accept)++ fun cancel(handle: Long) = receiver.cancel(handle)++ fun retire(handle: Long) = receiver.retire(handle)+}
share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropDiscovery.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropDiscovery.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropDiscovery.ktnew file mode 100644index 0000000000..b5c852d216--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropDiscovery.kt@@ -0,0 +1,249 @@+package com.vayunmathur.share.platform.airdrop++import android.annotation.SuppressLint+import android.bluetooth.BluetoothManager+import android.bluetooth.le.AdvertiseCallback+import android.bluetooth.le.AdvertiseData+import android.bluetooth.le.AdvertiseSettings+import android.content.Context+import android.net.Network+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import android.os.Build+import android.os.ParcelUuid+import android.os.ext.SdkExtensions+import com.vayunmathur.library.log.Log+import java.net.InetAddress+import java.security.SecureRandom+import java.util.concurrent.Executor+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlin.coroutines.resume++private const val TAG = "AirDropDiscovery"++const val AIRDROP_SERVICE_TYPE = "_airdrop._tcp"++/**+ * The `flags` TXT value Mosey advertises: its Phenotype default 1161 (`dlh.g()`), rendered as+ * uppercase hex (`cen`).+ */+private const val AIRDROP_TXT_FLAGS = "489"++private const val NSD_NETWORK_EXTENSION = 3++/** A resolved `_airdrop._tcp` record, before `/Discover` has told us its name. */+data class AirDropPeer(+ val serviceName: String,+ val address: InetAddress,+ val port: Int,+)++/**+ * mDNS for AirDrop, scoped to whichever network the link runs on, plus the BLE advertisement+ * that wakes Apple receivers' AWDL so they answer it.+ */+class AirDropDiscovery(private val context: Context) {++ private val nsd: NsdManager? = context.getSystemService(NsdManager::class.java)+ private var registration: NsdManager.RegistrationListener? = null+ private val resolveLock = Mutex()+ private val mainExecutor: Executor get() = context.mainExecutor++ /** Instance name we advertise under, so a browse can drop our own record. */+ @Volatile+ var ownServiceName: String? = null+ private set++ // Broad catch is deliberate: NSD throws undocumented RuntimeExceptions on some stacks.+ @Suppress("TooGenericExceptionCaught")+ fun advertise(serviceName: String, port: Int, network: Network?) {+ val mgr = nsd ?: return+ unadvertise()+ val info = NsdServiceInfo().apply {+ this.serviceName = serviceName+ serviceType = AIRDROP_SERVICE_TYPE+ this.port = port+ setAttribute("flags", AIRDROP_TXT_FLAGS)+ if (network != null && canScopeToNetwork()) this.network = network+ }+ val listener = object : NsdManager.RegistrationListener {+ override fun onServiceRegistered(info: NsdServiceInfo) {+ ownServiceName = info.serviceName+ Log.status(TAG, "advertising $AIRDROP_SERVICE_TYPE as ${info.serviceName} on $port (network=$network)")+ }++ override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {+ Log.status(TAG, "AirDrop registration failed: $errorCode")+ }++ override fun onServiceUnregistered(info: NsdServiceInfo) = Unit+ override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) = Unit+ }+ ownServiceName = serviceName+ registration = listener+ try {+ mgr.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)+ } catch (e: Exception) {+ Log.status(TAG, "registerService failed", e)+ registration = null+ }+ }++ fun unadvertise() {+ val listener = registration ?: return+ runCatching { nsd?.unregisterService(listener) }+ registration = null+ ownServiceName = null+ }++ /** `NsdServiceInfo.setNetwork` arrived in the T extension SDK 3. */+ private fun canScopeToNetwork(): Boolean =+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+ SdkExtensions.getExtensionVersion(Build.VERSION_CODES.TIRAMISU) >= NSD_NETWORK_EXTENSION++ /** Browses `_airdrop._tcp` on [network] and emits each record once it resolves. */+ // Broad catch is deliberate: NSD throws undocumented RuntimeExceptions on some stacks.+ @Suppress("TooGenericExceptionCaught")+ fun browse(network: Network?): Flow<AirDropPeer> = callbackFlow {+ val mgr = nsd ?: run {+ close()+ return@callbackFlow+ }+ val producer = this+ val listener = object : NsdManager.DiscoveryListener {+ override fun onDiscoveryStarted(serviceType: String) {+ Log.dev(TAG, "browsing $serviceType on $network")+ }++ override fun onServiceFound(info: NsdServiceInfo) {+ if (info.serviceName == ownServiceName) return+ producer.launch {+ // The pre-U resolver handles one request at a time and fails the rest outright.+ val resolved = resolveLock.withLock { resolve(mgr, info) } ?: return@launch+ val host = resolved.host ?: return@launch+ if (resolved.port > 0) trySend(AirDropPeer(resolved.serviceName, host, resolved.port))+ }+ }++ override fun onServiceLost(info: NsdServiceInfo) = Unit+ override fun onDiscoveryStopped(serviceType: String) = Unit++ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {+ Log.status(TAG, "AirDrop browse failed: $errorCode")+ close()+ }++ override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit+ }+ try {+ if (network != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ mgr.discoverServices(AIRDROP_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, network, mainExecutor, listener)+ } else {+ mgr.discoverServices(AIRDROP_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)+ }+ } catch (e: Exception) {+ Log.status(TAG, "discoverServices failed", e)+ close(e)+ return@callbackFlow+ }+ awaitClose { runCatching { mgr.stopServiceDiscovery(listener) } }+ }++ @Suppress("DEPRECATION")+ private suspend fun resolve(mgr: NsdManager, info: NsdServiceInfo): NsdServiceInfo? =+ suspendCancellableCoroutine { cont ->+ val listener = object : NsdManager.ResolveListener {+ override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {+ Log.dev(TAG, "resolve ${info.serviceName} failed: $errorCode")+ if (cont.isActive) cont.resume(null)+ }++ override fun onServiceResolved(info: NsdServiceInfo) {+ if (cont.isActive) cont.resume(info)+ }+ }+ runCatching { mgr.resolveService(info, listener) }.onFailure { if (cont.isActive) cont.resume(null) }+ }+}++/**+ * The BLE advertisement a Mosey sender runs while it looks for receivers (`cce.H`): Apple+ * manufacturer data of type `0x05` (AirDrop), version 1, eight random bytes where Apple puts+ * truncated contact hashes, plus Google's `0xFCF1` service UUID so other Mosey receivers can+ * tell it is not an Apple sender. Apple devices wake their AirDrop listener on seeing it.+ */+class AirDropBleAdvertiser(private val context: Context) {++ private var callback: AdvertiseCallback? = null++ @SuppressLint("MissingPermission")+ fun start() {+ if (callback != null) return+ val advertiser = context.getSystemService(BluetoothManager::class.java)?.adapter?.bluetoothLeAdvertiser ?: run {+ Log.status(TAG, "no BLE advertiser; Apple receivers may not wake up")+ return+ }+ val settings = AdvertiseSettings.Builder()+ .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)+ .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)+ .setConnectable(false)+ .also(::setNonResolvableAddress)+ .build()+ val data = AdvertiseData.Builder()+ .addManufacturerData(APPLE_COMPANY_ID, payload())+ .addServiceUuid(MOSEY_SERVICE_UUID)+ .build()+ val cb = object : AdvertiseCallback() {+ override fun onStartFailure(errorCode: Int) {+ Log.status(TAG, "AirDrop BLE advertise failed: $errorCode")+ }+ }+ callback = cb+ runCatching { advertiser.startAdvertising(settings, data, cb) }+ .onFailure { Log.status(TAG, "startAdvertising threw", it); callback = null }+ }++ @SuppressLint("MissingPermission")+ fun stop() {+ val cb = callback ?: return+ callback = null+ runCatching {+ context.getSystemService(BluetoothManager::class.java)?.adapter?.bluetoothLeAdvertiser?.stopAdvertising(cb)+ }+ }++ /** `setOwnAddressType(ADDRESS_TYPE_RANDOM_NON_RESOLVABLE)` is @SystemApi; best effort. */+ private fun setNonResolvableAddress(builder: AdvertiseSettings.Builder) {+ runCatching {+ AdvertiseSettings.Builder::class.java+ .getMethod("setOwnAddressType", Int::class.javaPrimitiveType)+ .invoke(builder, ADDRESS_TYPE_RANDOM_NON_RESOLVABLE)+ }+ }++ private fun payload(): ByteArray = ByteArray(PAYLOAD_SIZE).also {+ it[0] = AIRDROP_TYPE+ it[1] = AIRDROP_LENGTH+ it[VERSION_INDEX] = 1+ val random = ByteArray(RANDOM_LENGTH).also(SecureRandom()::nextBytes)+ random.copyInto(it, RANDOM_OFFSET)+ }++ private companion object {+ const val APPLE_COMPANY_ID = 0x004C+ val MOSEY_SERVICE_UUID: ParcelUuid = ParcelUuid.fromString("0000fcf1-0000-1000-8000-00805f9b34fb")+ const val ADDRESS_TYPE_RANDOM_NON_RESOLVABLE = 2+ const val PAYLOAD_SIZE = 20+ const val AIRDROP_TYPE: Byte = 0x05+ const val AIRDROP_LENGTH: Byte = 0x12+ const val VERSION_INDEX = 10+ const val RANDOM_OFFSET = 11+ const val RANDOM_LENGTH = 8+ }+}
share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.ktnew file mode 100644index 0000000000..34cfa2ca8b--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt@@ -0,0 +1,266 @@+package com.vayunmathur.share.platform.airdrop++import com.vayunmathur.library.log.Log+import com.vayunmathur.share.domain.airdrop.AirDropMessages+import com.vayunmathur.share.domain.airdrop.BinaryPlist+import com.vayunmathur.share.domain.airdrop.Cpio+import com.vayunmathur.share.domain.airdrop.DvZip+import com.vayunmathur.share.domain.airdrop.Uti+import com.vayunmathur.share.domain.protocol.PendingFile+import com.vayunmathur.share.domain.protocol.ShareState+import com.vayunmathur.share.network.airdrop.AirDropHttp+import com.vayunmathur.share.platform.IncomingTransfer+import com.vayunmathur.share.platform.ReceivedFile+import com.vayunmathur.share.platform.ReceivedFileStore+import java.io.BufferedInputStream+import java.io.File+import java.io.InputStream+import java.net.InetAddress+import java.util.concurrent.atomic.AtomicLong+import java.util.zip.GZIPInputStream+import java.util.zip.ZipInputStream+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.withTimeoutOrNull++private const val TAG = "AirDropReceiver"++/** How long an Ask waits for the user; Mosey's notification shares the 60 s of Quick Share. */+private const val ASK_TIMEOUT_MS = 60_000L++/** Mosey's free-space margin: refuse unless 2.5x the announced size is available (`cdw`). */+private const val SPACE_MARGIN = 2.5++private const val GZIP_MAGIC_0 = 0x1F+private const val GZIP_MAGIC_1 = 0x8B+private const val COPY_BUFFER = 64 * 1024++/** One incoming AirDrop transfer, from the Ask through the Upload. */+class AirDropIncoming internal constructor(+ override val sessionHandle: Long,+ val ask: AirDropMessages.AskRequest,+ val remote: InetAddress,+) : IncomingTransfer {+ internal val decision = CompletableDeferred<Boolean>()++ override val state = MutableStateFlow(ShareState.AwaitingAccept)+ override val pendingFiles: StateFlow<List<PendingFile>> = MutableStateFlow(+ ask.files.filterNot { it.isDirectory }.map {+ PendingFile(it.fileName, it.fileSize.coerceAtLeast(0), Uti.mimeTypeOf(it.fileType) ?: ReceivedFileStore.GENERIC_MIME_TYPE)+ },+ )+ override val receivedFiles = MutableStateFlow<List<ReceivedFile>>(emptyList())+ override val bytesReceived = MutableStateFlow(0L)+ override val expectedTotalBytes: StateFlow<Long> = MutableStateFlow(ask.totalBytes)+ override val error = MutableStateFlow<String?>(null)+ override val displayName: String get() = ask.senderComputerName++ internal fun fail(reason: String) {+ if (state.value == ShareState.Completed || state.value == ShareState.Failed) return+ error.value = reason+ state.value = ShareState.Failed+ decision.complete(false)+ }+}++/**+ * The receiving half of AirDrop: answers `/Discover`, holds `/Ask` until the user decides,+ * and unpacks `/Upload` into [ReceivedFileStore].+ *+ * Transfers surface through [incoming] as [IncomingTransfer]s, so the same notifications that+ * carry Quick Share requests carry these.+ */+class AirDropReceiver(+ private val store: ReceivedFileStore,+ private val localName: () -> String,+ private val freeBytes: () -> Long,+ private val onTransfer: (remote: InetAddress, started: Boolean) -> Unit,+) {+ private val nextHandle = AtomicLong(-1)+ private val sessions = mutableMapOf<Long, AirDropIncoming>()+ private val lock = Any()++ private val _incoming = MutableStateFlow<List<AirDropIncoming>>(emptyList())+ val incoming: StateFlow<List<AirDropIncoming>> = _incoming.asStateFlow()++ fun sessionFor(handle: Long): AirDropIncoming? = synchronized(lock) { sessions[handle] }++ fun accept(handle: Long, accept: Boolean): Int {+ val session = sessionFor(handle) ?: return -1+ if (!accept) session.fail("declined")+ session.decision.complete(accept)+ return 0+ }++ fun cancel(handle: Long) {+ sessionFor(handle)?.fail("cancelled")+ }++ fun retire(handle: Long) {+ synchronized(lock) {+ sessions.remove(handle)+ _incoming.value = sessions.values.toList()+ }+ }++ val hasActiveTransfers: Boolean+ get() = synchronized(lock) { sessions.values.any { it.state.value == ShareState.Transferring } }++ suspend fun handle(request: AirDropHttp.Request, remote: InetAddress): AirDropHttp.Response =+ when (request.path) {+ "/Discover" -> discover()+ "/Ask" -> ask(request, remote)+ "/Upload" -> upload(request, remote)+ else -> AirDropHttp.Response(404)+ }++ private fun discover(): AirDropHttp.Response {+ val body = AirDropMessages.DiscoverResponse(+ receiverComputerName = localName(),+ manufacturer = AirDropMessages.MANUFACTURER_GOOGLE,+ mediaCapabilities = AirDropMessages.DEFAULT_MEDIA_CAPABILITIES,+ ).toPlist()+ return plistResponse(body)+ }++ // Broad catch is deliberate: a malformed plist from a peer is a 401, not a crash.+ @Suppress("TooGenericExceptionCaught")+ private suspend fun ask(request: AirDropHttp.Request, remote: InetAddress): AirDropHttp.Response {+ val ask = try {+ AirDropMessages.AskRequest.fromPlist(BinaryPlist.decodeDict(request.readBody()))+ } catch (e: Exception) {+ Log.status(TAG, "unreadable Ask from ${remote.hostAddress}", e)+ null+ } ?: return AirDropHttp.Response(401)+ if (ask.items.isNotEmpty() && ask.files.isEmpty()) {+ // Links arrive as Items with no archive; nowhere to stage them yet.+ Log.status(TAG, "declining link-only Ask from ${ask.senderComputerName}")+ return AirDropHttp.Response(401)+ }+ if (freeBytes() < ask.totalBytes * SPACE_MARGIN) {+ Log.status(TAG, "not enough space for ${ask.totalBytes} bytes from ${ask.senderComputerName}")+ return AirDropHttp.Response(401)+ }+ val session = AirDropIncoming(nextHandle.getAndDecrement(), ask, remote)+ synchronized(lock) {+ if (sessions.values.any { it.state.value == ShareState.Transferring }) {+ return AirDropHttp.Response(401)+ }+ sessions[session.sessionHandle] = session+ _incoming.value = sessions.values.toList()+ }+ Log.status(TAG, "Ask from ${ask.senderComputerName} (${ask.senderModelName}): ${ask.files.size} file(s)")+ val accepted = withTimeoutOrNull(ASK_TIMEOUT_MS) { session.decision.await() } ?: false+ if (!accepted) {+ session.fail("timed out")+ return AirDropHttp.Response(401)+ }+ session.state.value = ShareState.Transferring+ return plistResponse(+ mapOf(+ "ReceiverModelName" to android.os.Build.MODEL,+ "ReceiverComputerName" to localName(),+ ),+ )+ }++ // Broad catch is deliberate: a bad archive fails this transfer and nothing else.+ @Suppress("TooGenericExceptionCaught")+ private fun upload(request: AirDropHttp.Request, remote: InetAddress): AirDropHttp.Response {+ val transferId = request.headers["transferid"]+ val session = synchronized(lock) {+ sessions.values.firstOrNull {+ it.state.value == ShareState.Transferring &&+ (if (transferId != null) it.ask.transferId == transferId else it.remote == remote)+ }+ } ?: run {+ Log.status(TAG, "Upload from ${remote.hostAddress} matches no accepted Ask")+ return AirDropHttp.Response(400)+ }+ onTransfer(remote, true)+ return try {+ val written = extract(request.headers["content-type"], request.body) { session.bytesReceived.value += it }+ session.receivedFiles.value = written.map {+ ReceivedFile(it.name, it.length(), ReceivedFileStore.mimeTypeOf(it), store.contentUri(it))+ }+ session.state.value = ShareState.Completed+ Log.status(TAG, "received ${written.size} file(s) from ${session.displayName}")+ AirDropHttp.Response(200)+ } catch (e: Exception) {+ Log.status(TAG, "Upload from ${session.displayName} failed", e)+ session.fail(e.message ?: "upload failed")+ AirDropHttp.Response(500)+ } finally {+ onTransfer(remote, false)+ }+ }++ /** Unpacks the body by its declared type, sniffing gzip, which Apple wraps cpio in. */+ private fun extract(contentType: String?, body: InputStream, onBytes: (Long) -> Unit): List<File> {+ val type = contentType?.substringBefore(';')?.trim()?.lowercase()+ val buffered = BufferedInputStream(body)+ return when (type) {+ AirDropMessages.CONTENT_TYPE_DVZIP -> extractCpio(DvZip.Reader(buffered), onBytes)+ AirDropMessages.CONTENT_TYPE_ZIP -> extractZip(ZipInputStream(buffered), onBytes)+ else -> extractCpio(if (isGzip(buffered)) GZIPInputStream(buffered) else buffered, onBytes)+ }+ }++ private fun extractCpio(input: InputStream, onBytes: (Long) -> Unit): List<File> {+ val reader = Cpio.Reader(input)+ val written = mutableListOf<File>()+ while (true) {+ val (entry, content) = reader.next() ?: break+ if (!entry.isFile) continue+ val name = AirDropMessages.safeRelativePath(entry.name) ?: continue+ written += writeEntry(name, content, onBytes)+ }+ return written+ }++ private fun extractZip(zip: ZipInputStream, onBytes: (Long) -> Unit): List<File> {+ val written = mutableListOf<File>()+ while (true) {+ val entry = zip.nextEntry ?: break+ if (entry.isDirectory) continue+ val name = AirDropMessages.safeRelativePath(entry.name) ?: continue+ written += writeEntry(name, zip, onBytes)+ }+ return written+ }++ private fun writeEntry(relativePath: String, content: InputStream, onBytes: (Long) -> Unit): File {+ val file = store.newFile(relativePath)+ try {+ file.outputStream().use { out ->+ val buf = ByteArray(COPY_BUFFER)+ while (true) {+ val n = content.read(buf)+ if (n < 0) break+ out.write(buf, 0, n)+ onBytes(n.toLong())+ }+ }+ } catch (e: java.io.IOException) {+ file.delete()+ throw e+ }+ return file+ }++ private fun isGzip(input: BufferedInputStream): Boolean {+ input.mark(2)+ val b0 = input.read()+ val b1 = input.read()+ input.reset()+ return b0 == GZIP_MAGIC_0 && b1 == GZIP_MAGIC_1+ }++ private fun plistResponse(body: Map<String, Any?>) = AirDropHttp.Response(+ 200,+ mapOf("Content-Type" to AirDropMessages.CONTENT_TYPE_PLIST),+ BinaryPlist.encode(body),+ )+}
share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.ktnew file mode 100644index 0000000000..c61a334f72--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.kt@@ -0,0 +1,119 @@+package com.vayunmathur.share.platform.airdrop++import android.os.Build+import com.vayunmathur.library.log.Log+import com.vayunmathur.share.domain.airdrop.AirDropMessages+import com.vayunmathur.share.domain.airdrop.BinaryPlist+import com.vayunmathur.share.domain.airdrop.Cpio+import com.vayunmathur.share.domain.airdrop.DvZip+import com.vayunmathur.share.network.airdrop.AirDropHttpClient+import com.vayunmathur.share.platform.airdrop.link.AirDropLink+import java.io.File+import java.io.FilterInputStream+import java.io.InputStream+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++private const val TAG = "AirDropSender"++/** Discover is answered immediately; anything slower is a peer we cannot use. */+private const val DISCOVER_TIMEOUT_MS = 5_000++/** Ask blocks until the receiving user decides, and the upload can stall on a busy link. */+private const val TRANSFER_TIMEOUT_MS = 120_000++/** The sending half of AirDrop: `/Discover` for a name, then `/Ask` and a dvzip `/Upload`. */+class AirDropSender(private val localName: () -> String) {++ sealed interface Result {+ data object Sent : Result+ data object Declined : Result+ data class Failed(val reason: String) : Result+ }++ private val senderId = AirDropMessages.randomShortId()++ /**+ * The receiver's advertised name, or null when it is unreachable, unreadable, or a Google+ * device — which Mosey skips because Quick Share already reaches it (`cbz`).+ */+ // Broad catch is deliberate: any failure to talk to a candidate means "not listed".+ @Suppress("TooGenericExceptionCaught")+ suspend fun discover(peer: AirDropPeer, link: AirDropLink): AirDropMessages.DiscoverResponse? = withContext(Dispatchers.IO) {+ try {+ AirDropHttpClient(peer.address, peer.port, link.socketFactory, DISCOVER_TIMEOUT_MS).use { client ->+ val resp = client.postPlist("/Discover", BinaryPlist.encode(emptyMap<String, Any?>()), keepAlive = false)+ if (!resp.isSuccessful) return@withContext null+ val parsed = AirDropMessages.DiscoverResponse.fromPlist(BinaryPlist.decodeDict(resp.body)) ?: return@withContext null+ if (parsed.manufacturer.equals(AirDropMessages.MANUFACTURER_GOOGLE, ignoreCase = true)) {+ Log.dev(TAG, "skipping Google device ${parsed.receiverComputerName}")+ return@withContext null+ }+ parsed+ }+ } catch (e: Exception) {+ Log.dev(TAG, "Discover ${peer.serviceName} failed: ${e.message}")+ null+ }+ }++ // Broad catch is deliberate: a transfer failure is reported, never thrown at the UI.+ @Suppress("TooGenericExceptionCaught")+ suspend fun send(+ peer: AirDropPeer,+ link: AirDropLink,+ files: List<File>,+ onProgress: (sent: Long, total: Long) -> Unit,+ ): Result = withContext(Dispatchers.IO) {+ val transferId = UUID.randomUUID().toString()+ val total = files.sumOf { it.length() }+ val ask = AirDropMessages.AskRequest(+ senderComputerName = localName(),+ senderModelName = Build.MODEL,+ senderId = senderId,+ files = files.map { AirDropMessages.AskFile.forFile(it.name, it.length()) },+ transferId = transferId,+ )+ try {+ AirDropHttpClient(peer.address, peer.port, link.socketFactory, TRANSFER_TIMEOUT_MS).use { client ->+ val askResp = client.postPlist("/Ask", BinaryPlist.encode(ask.toPlist()))+ if (!askResp.isSuccessful) {+ Log.status(TAG, "Ask declined by ${peer.serviceName}: ${askResp.status}")+ return@withContext Result.Declined+ }+ link.onTransferStarted(peer.address)+ try {+ var sent = 0L+ val upload = client.upload(AirDropMessages.CONTENT_TYPE_DVZIP, total, transferId) { body ->+ val dv = DvZip.Writer(body)+ val cpio = Cpio.Writer(dv)+ for (file in files) {+ file.inputStream().use { raw ->+ val counted = Counting(raw) { n ->+ sent += n+ onProgress(sent, total)+ }+ cpio.file("./${file.name}", file.length(), counted)+ }+ }+ cpio.finish()+ dv.close()+ }+ if (upload.isSuccessful) Result.Sent else Result.Failed("receiver answered ${upload.status}")+ } finally {+ link.onTransferEnded(peer.address)+ }+ }+ } catch (e: Exception) {+ Log.status(TAG, "send to ${peer.serviceName} failed", e)+ Result.Failed(e.message ?: e.javaClass.simpleName)+ }+ }++ private class Counting(input: InputStream, private val onBytes: (Long) -> Unit) : FilterInputStream(input) {+ override fun read(): Int = super.read().also { if (it >= 0) onBytes(1) }+ override fun read(b: ByteArray, off: Int, len: Int): Int =+ super.read(b, off, len).also { if (it > 0) onBytes(it.toLong()) }+ }+}
share/src/main/java/com/vayunmathur/share/platform/airdrop/link/AirDropLink.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/AirDropLink.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/AirDropLink.ktnew file mode 100644index 0000000000..b671e2df86--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/AirDropLink.kt@@ -0,0 +1,191 @@+package com.vayunmathur.share.platform.airdrop.link++import android.annotation.SuppressLint+import android.content.Context+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.net.wifi.WifiManager+import android.os.Binder+import android.os.Build+import android.telephony.TelephonyManager+import androidx.annotation.RequiresApi+import com.vayunmathur.library.log.Log+import java.net.Inet6Address+import java.net.InetAddress+import java.util.Locale+import javax.net.SocketFactory++private const val TAG = "AirDropLink"++/**+ * The network AirDrop runs over: Mosey's AWDL interface when the device has the HAL, else the+ * phone's ordinary Wi-Fi network.+ *+ * Only Mosey reaches Apple devices in practice — iPhones and Macs only offer AirDrop over+ * AWDL — but the Wi-Fi link keeps the whole stack exercisable on hardware without the HAL.+ */+sealed interface AirDropLink {+ val kind: Kind++ /** Network to scope mDNS and sockets to, or null for the system default. */+ val network: Network?++ val socketFactory: SocketFactory get() = network?.socketFactory ?: SocketFactory.getDefault()++ /** Brings the link up; false if it could not be. Idempotent. */+ suspend fun activate(): Boolean++ fun deactivate()++ fun onTransferStarted(peer: InetAddress) = Unit+ fun onTransferEnded(peer: InetAddress) = Unit++ enum class Kind { Mosey, WifiLan }+}++class WifiLanLink(private val context: Context) : AirDropLink {+ override val kind = AirDropLink.Kind.WifiLan++ override val network: Network?+ get() {+ val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null+ return cm.activeNetwork?.takeIf {+ cm.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true+ }+ }++ override suspend fun activate(): Boolean = true++ override fun deactivate() = Unit+}++/**+ * Drives the Mosey HAL and publishes its `mosey0` interface as a local network, as Mosey's+ * `MoseyController` does.+ *+ * Needs, on the OS side: the HAL itself, `NETWORK_FACTORY`, `CONNECTIVITY_USE_RESTRICTED_NETWORKS`+ * and `NEARBY_WIFI_DEVICES` granted to a privileged :share, and hidden-API access for+ * `ServiceManager`. Any of those missing makes [activate] return false, and the selector falls+ * back to [WifiLanLink]. API 34+: Mosey itself requires a far newer OS, and the agent APIs+ * it needs are not all present earlier.+ */+@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)+class MoseyLink(private val context: Context, private val hal: MoseyHal) : AirDropLink {+ override val kind = AirDropLink.Kind.Mosey++ private val token = Binder()+ private var agent: MoseyNetworkAgent? = null+ private var countryCode: String? = null++ override val network: Network? get() = agent?.network++ // Broad catch is deliberate: the HAL is a binder/shared-library boundary and the network+ // agent calls throw SecurityException plus undocumented RuntimeExceptions without privilege.+ @Suppress("TooGenericExceptionCaught")+ override suspend fun activate(): Boolean {+ if (agent?.network != null) return true+ val country = countryCode() ?: run {+ Log.status(TAG, "no regulatory country code yet; not starting Mosey")+ return false+ }+ countryCode = country+ return try {+ val hopping = MoseyConfig.isChannelHoppingSupported(runCatching { hal.hardwareCapability() }.getOrNull())+ val channels = channels()+ val sta = staChannel()+ val wifi = context.getSystemService(WifiManager::class.java)+ val dbs = wifi?.isDualBandSimultaneousSupported == true+ Log.status(+ TAG,+ "starting Mosey ${hal.backend.label} ${hal.version}: channels=${channels.toList()} " ++ "sta=$sta dbs=$dbs hopping=$hopping country=$country",+ )+ hal.update(country, MoseyConfig.staChannelUpdate(sta))+ hal.start(channels, token, MoseyConfig.start(channels, sta, dbs))+ val up = MoseyNetworkAgent.bringUp(context) ?: run {+ Log.status(TAG, "mosey0 never appeared; stopping the HAL")+ runCatching { hal.stop() }+ return false+ }+ agent = up+ true+ } catch (e: Exception) {+ Log.status(TAG, "Mosey start failed", e)+ runCatching { hal.stop() }+ false+ }+ }++ override fun deactivate() {+ agent?.tearDown()+ agent = null+ runCatching { hal.stop() }.onFailure { Log.status(TAG, "Mosey stop failed", it) }+ }++ override fun onTransferStarted(peer: InetAddress) = notifyDaemon(peer, started = true)++ override fun onTransferEnded(peer: InetAddress) = notifyDaemon(peer, started = false)++ /** The daemon keeps the AWDL link awake for a peer while a transfer to it is live. */+ private fun notifyDaemon(peer: InetAddress, started: Boolean) {+ val v6 = peer as? Inet6Address ?: return+ val country = countryCode ?: return+ val config = if (started) MoseyConfig.transferStarted(v6) else MoseyConfig.transferEnded(v6)+ runCatching { hal.update(country, config) }+ .onFailure { Log.status(TAG, "notify daemon (started=$started) failed", it) }+ }++ private fun channels(): IntArray {+ val wifi = context.getSystemService(WifiManager::class.java)+ return if (wifi?.is5GHzBandSupported == false) MoseyConfig.FALLBACK_CHANNELS else MoseyConfig.DEFAULT_CHANNELS+ }++ private fun staChannel(): Int? {+ val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null+ val caps = cm.activeNetwork?.let(cm::getNetworkCapabilities) ?: return null+ val info = caps.transportInfo as? android.net.wifi.WifiInfo ?: return null+ return frequencyToChannel(info.frequency)+ }++ /**+ * The framework's regulatory country (`WifiManager.getCountryCode`, @SystemApi), falling+ * back to the cellular network's. Never guessed: AWDL channels are regulated.+ */+ @SuppressLint("PrivateApi")+ private fun countryCode(): String? {+ val wifi = context.getSystemService(WifiManager::class.java)+ val fromWifi = runCatching { WifiManager::class.java.getMethod("getCountryCode").invoke(wifi) as String? }.getOrNull()+ val fromCell = context.getSystemService(TelephonyManager::class.java)?.networkCountryIso+ return (fromWifi ?: fromCell)?.takeIf { it.length == 2 }?.uppercase(Locale.ROOT)+ }++ private fun frequencyToChannel(mhz: Int): Int? = when (mhz) {+ 2484 -> 14+ in 2412..2472 -> (mhz - 2407) / 5+ in 5160..5885 -> (mhz - 5000) / 5+ in 5955..7115 -> (mhz - 5950) / 5+ else -> null+ }+}++/** Picks the best available link and reports which one, for logs and the send screen. */+object AirDropLinkSelector {++ data class Selection(val link: AirDropLink, val mosey: MoseyStatus)++ suspend fun select(context: Context): Selection {+ val app = context.applicationContext+ val status = MoseyDetector.detect(app)+ Log.status(TAG, "Mosey: ${status.detail}")+ if (status.available && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ val hal = MoseyDetector.open(app)+ if (hal != null) {+ val mosey = MoseyLink(app, hal)+ if (mosey.activate()) return Selection(mosey, status)+ Log.status(TAG, "Mosey present but could not be started; using Wi-Fi")+ }+ }+ return Selection(WifiLanLink(app).also { it.activate() }, status)+ }+}
share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyConfig.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyConfig.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyConfig.ktnew file mode 100644index 0000000000..73bc543cc9--- /dev/null+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyConfig.kt@@ -0,0 +1,163 @@+package com.vayunmathur.share.platform.airdrop.link++import java.io.ByteArrayOutputStream+import java.net.Inet6Address++/**+ * The opaque config blobs the Mosey HAL takes, hand-encoded as the protobuf-lite messages+ * Mosey builds (`btk` for `start`, `btn` for `update`, `btc` for the capability reply).+ *+ * Field numbers and the defaults below are recovered from Mosey's schema strings and its+ * Phenotype fallbacks (`dlr`). Live Phenotype values on a Pixel can differ; these are what a+ * Mosey build with no server config sends.+ */+object MoseyConfig {++ /** Mosey's default AWDL channels when nothing rules them out (`byt`). */+ val DEFAULT_CHANNELS = intArrayOf(149, 44)++ /** Its 2.4 GHz fallback when no 5 GHz channel is usable. */+ val FALLBACK_CHANNELS = intArrayOf(6)++ private const val BANDWIDTH_20MHZ = 0+ private const val BANDWIDTH_80MHZ = 2+ private const val BANDWIDTH_INVALID = -1++ /** `btm` constants as they land on the wire (`btm.a(i) = i - 2`). */+ private const val UPDATE_STA_CHANNEL = 1+ private const val UPDATE_TRANSFER_STARTED = 2+ private const val UPDATE_TRANSFER_ENDED = 3++ /** Six `btj` "DATA" entries, one per Phenotype-selected power profile slot. */+ private const val POWER_PROFILE_SLOTS
Diff truncated.