share: detekt clean (225 tests)
- Commit
4e103b1dcd7634b6fa34845f237200daac7b56c1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 01:03 UTC (21 days ago)
- Parents
616fdee
Fix all detekt findings in share by fixing code, not config (detekt.yml untouched, no baselines added): - UndocumentedPublicClass: KDoc for the module types. - AirDrop protocol magic numbers are named constants (DER/OID, HTTP, protobuf fields, Wi-Fi bands); BinaryPlist read/write split into per-kind helpers. - Catch cleanup: tests use catch (_:) with comments; AirDropController broad catch kept with narrow @Suppress justification; cpio/zip and HTTP keep-alive loops restructured. - MaxLineLength wrapped across the module. Verified: ./gradlew :share:detekt :share:testDevUnitTest :share:lint --max-workers=32 all pass (225 unit tests).
Diff
share/src/main/java/com/vayunmathur/share/Route.kt
diff --git a/share/src/main/java/com/vayunmathur/share/Route.kt b/share/src/main/java/com/vayunmathur/share/Route.ktindex a0ee78646d..6ed91e3dbe 100644--- a/share/src/main/java/com/vayunmathur/share/Route.kt+++ b/share/src/main/java/com/vayunmathur/share/Route.kt@@ -3,8 +3,10 @@ package com.vayunmathur.share import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Contract for route. */ @Serializable sealed interface Route : NavKey {+ /** Singleton holding share state and operations. */ @Serializable data object Share : Route }
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.ktindex 68e8636a51..b2e1f98f58 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/AirDropMessages.kt@@ -21,6 +21,7 @@ object AirDropMessages { /** What Mosey and OpenDrop both advertise; Apple peers only check that it parses. */ val DEFAULT_MEDIA_CAPABILITIES: ByteArray = """{"Version":1}""".toByteArray(Charsets.UTF_8) + /** Immutable value describing discover response. */ data class DiscoverResponse( val receiverComputerName: String, val manufacturer: String? = null,@@ -32,6 +33,7 @@ object AirDropMessages { manufacturer?.let { put("Manufacturer", it) } } + /** Shared constants and helpers for DiscoverResponse. */ companion object { fun fromPlist(map: Map<String, Any?>): DiscoverResponse? { val name = (map["ReceiverComputerName"] as? String)?.takeIf { it.isNotBlank() } ?: return null@@ -44,6 +46,7 @@ object AirDropMessages { } } + /** Immutable value describing ask file. */ data class AskFile( val fileName: String, val fileType: String,@@ -63,6 +66,7 @@ object AirDropMessages { put("ShouldConvertMediaFormats", false) } + /** Shared constants and helpers for AskFile. */ companion object { fun fromPlist(map: Map<*, *>): AskFile? { val name = (map["FileName"] as? String)?.takeIf { it.isNotBlank() } ?: return null@@ -86,6 +90,7 @@ object AirDropMessages { } } + /** Immutable value describing ask request. */ data class AskRequest( val senderComputerName: String, val senderModelName: String,@@ -110,6 +115,7 @@ object AirDropMessages { /** Sum of announced sizes, treating Apple's "unknown" (negative) as zero. */ val totalBytes: Long get() = files.sumOf { it.fileSize.coerceAtLeast(0) } + /** Shared constants and helpers for AskRequest. */ companion object { fun fromPlist(map: Map<String, Any?>): AskRequest? { val files = (map["Files"] as? List<*>).orEmpty()@@ -122,7 +128,8 @@ object AirDropMessages { else -> null } return AskRequest(- senderComputerName = (map["SenderComputerName"] as? String)?.takeIf { it.isNotBlank() } ?: "AirDrop",+ senderComputerName = (map["SenderComputerName"] as? String)+ ?.takeIf { it.isNotBlank() } ?: "AirDrop", senderModelName = map["SenderModelName"] as? String ?: "", senderId = map["SenderID"] as? String ?: "", files = files,
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.ktindex 79dd61c99d..7adeedfc8f 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/BinaryPlist.kt@@ -17,6 +17,7 @@ object BinaryPlist { private const val MAGIC = "bplist00" private const val TRAILER_SIZE = 32 + /** Format Exception: a string implementation for format exception. */ class FormatException(message: String) : IllegalArgumentException(message) fun encode(root: Any?): ByteArray = Encoder().encode(root)@@ -73,6 +74,14 @@ object BinaryPlist { } private fun writeObject(out: ByteArrayOutputStream, value: Any?, refSize: Int, firstChildRef: Int) {+ when (value) {+ is List<*> -> writeList(out, value, refSize, firstChildRef)+ is Map<*, *> -> writeDict(out, value, refSize, firstChildRef)+ else -> writeScalar(out, value)+ }+ }++ private fun writeScalar(out: ByteArrayOutputStream, value: Any?) { when (value) { null -> out.write(0x00) is Boolean -> out.write(if (value) 0x09 else 0x08)@@ -87,27 +96,29 @@ object BinaryPlist { 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 writeList(out: ByteArrayOutputStream, value: List<*>, refSize: Int, firstChildRef: Int) {+ writeMarker(out, 0xA0, value.size)+ var ref = firstChildRef+ value.forEach { child ->+ writeSized(out, ref.toLong(), refSize)+ ref += subtreeSize(child)+ }+ }++ private fun writeDict(out: ByteArrayOutputStream, value: Map<*, *>, refSize: Int, firstChildRef: Int) {+ 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)+ }+ }+ private fun writeInt(out: ByteArrayOutputStream, v: Long) { val (marker, size) = when (v) { in 0L..0xFFL -> 0x10 to 1@@ -169,14 +180,19 @@ object BinaryPlist { 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- ) {+ if (!isTrailerValid(top, t)) { throw FormatException("corrupt trailer") } return readObject(top) } + private fun isTrailerValid(top: Long, trailerStart: Int): Boolean {+ val sizesValid = offsetSize in 1..8 && refSize in 1..8+ val topValid = top < numObjects+ val tableFits = offsetTableOffset + numObjects * offsetSize <= trailerStart+ return sizesValid && topValid && tableFits+ }+ 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)@@ -192,12 +208,7 @@ object BinaryPlist { 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")- }+ 0x0 -> readSimple(info, marker) 0x1 -> readInt(pos + 1, 1 shl info) 0x2 -> readReal(pos + 1, 1 shl info) 0x3 -> readReal(pos + 1, 8)@@ -214,22 +225,8 @@ object BinaryPlist { 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- }+ 0xA -> readArray(pos, info)+ 0xD -> readDict(pos, info) else -> throw FormatException("unsupported marker $marker") } } finally {@@ -237,6 +234,31 @@ object BinaryPlist { } } + private fun readSimple(info: Int, marker: Int): Any? = when (info) {+ 0x0 -> null+ 0x8 -> false+ 0x9 -> true+ else -> throw FormatException("bad simple marker $marker")+ }++ private fun readArray(pos: Int, info: Int): List<Any?> {+ val (count, start) = countAt(pos, info)+ checkedEnd(start, count * refSize)+ return List(count) { i -> readObject(readSized(start + i * refSize, refSize)) }+ }++ private fun readDict(pos: Int, info: Int): Map<String, Any?> {+ 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))+ }+ return map+ }+ 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
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.ktindex 058245b22a..77dfdc01a9 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Cpio.kt@@ -31,6 +31,7 @@ object Cpio { /** Longest name accepted on read; a hostile header must not make us allocate gigabytes. */ private const val MAX_NAME = 4096 + /** Format Exception: a string implementation for format exception. */ class FormatException(message: String) : IOException(message) /** Streams an odc archive. Close (or [finish]) to write the trailer. */@@ -84,6 +85,7 @@ object Cpio { } } + /** Type representing entry. */ class Entry( val name: String, val mode: Int,
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.ktindex e2f10d473a..e6cff40831 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/DvZip.kt@@ -24,6 +24,7 @@ object DvZip { /** Longest chunk accepted on read, compressed or not, so a hostile length cannot OOM us. */ private const val MAX_CHUNK = 16 * 1024 * 1024 + /** Writer: a output stream implementation for writer. */ class Writer(private val out: OutputStream) : OutputStream() { private val buffer = ByteArray(CHUNK_SIZE) private var filled = 0@@ -85,6 +86,7 @@ object DvZip { } } + /** Reader: a input stream implementation for reader. */ class Reader(private val input: InputStream) : InputStream() { private val inflater = Inflater() private var chunk = ByteArray(0)
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.ktindex 63ba553138..2c762eb4b2 100644--- a/share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/airdrop/Uti.kt@@ -8,6 +8,7 @@ package com.vayunmathur.share.domain.airdrop */ object Uti { + /** Immutable value describing type; carries uti, bundleId. */ data class Type(val uti: String, val bundleId: String) const val FOLDER = "public.folder"
share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt
diff --git a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.ktindex e032f2d345..0df71e3e43 100644--- a/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt+++ b/share/src/main/java/com/vayunmathur/share/domain/protocol/ShareSession.kt@@ -6,6 +6,7 @@ import java.nio.ByteOrder import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json +/** Immutable value describing pending file; carries name, sizeBytes, mimeType. */ @Serializable data class PendingFile(val name: String, val sizeBytes: Long, val mimeType: String) @@ -35,6 +36,7 @@ enum class ShareState(val code: Int) { Failed(4), Unknown(-1); + /** Shared constants and helpers for ShareState. */ companion object { fun fromCode(code: Int): ShareState = entries.firstOrNull { it.code == code } ?: Unknown }
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.ktindex c4de0c1244..0f7c62910f 100644--- a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.kt+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttp.kt@@ -20,10 +20,21 @@ object AirDropHttp { private const val MAX_LINE = 8192 private const val MAX_HEADERS = 100+ private const val MIN_REQUEST_LINE_PARTS = 3+ private const val BYTE_MASK = 0xFF+ private const val CHUNK_SIZE_RADIX = 16++ // HTTP status codes named where the text table below is keyed by them.+ private const val STATUS_OK = 200+ private const val STATUS_BAD_REQUEST = 400+ private const val STATUS_UNAUTHORIZED = 401+ private const val STATUS_NOT_FOUND = 404+ private const val STATUS_INTERNAL_SERVER_ERROR = 500 /** Largest plist body read into memory; `/Upload` is the only big body and is streamed. */ const val MAX_PLIST_BODY = 4 * 1024 * 1024 + /** Protocol Exception: a string implementation for protocol exception. */ class ProtocolException(message: String) : IOException(message) /** Header names are stored lowercased; HTTP header names are case-insensitive. */@@ -37,10 +48,12 @@ object AirDropHttp { override fun toString(): String = map.toString() } + /** Request: a string implementation for request. */ 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) } + /** Type representing response. */ class Response( val status: Int, val headers: Map<String, String> = emptyMap(),@@ -52,7 +65,7 @@ object AirDropHttp { 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")+ if (parts.size < MIN_REQUEST_LINE_PARTS) throw ProtocolException("bad request line: $line") val headers = readHeaders(input) return Request(parts[0], parts[1].substringBefore('?'), headers, bodyStream(input, headers, requestBody = true)) }@@ -171,11 +184,11 @@ object AirDropHttp { } private fun reason(status: Int): String = when (status) {- 200 -> "OK"- 400 -> "Bad Request"- 401 -> "Unauthorized"- 404 -> "Not Found"- 500 -> "Internal Server Error"+ STATUS_OK -> "OK"+ STATUS_BAD_REQUEST -> "Bad Request"+ STATUS_UNAUTHORIZED -> "Unauthorized"+ STATUS_NOT_FOUND -> "Not Found"+ STATUS_INTERNAL_SERVER_ERROR -> "Internal Server Error" else -> "Status" } @@ -209,15 +222,20 @@ object AirDropHttp { override fun read(): Int { val one = ByteArray(1)- return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xFF+ return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and BYTE_MASK+ }++ /** The next chunk's size; throws on a truncated or unparseable size line. */+ private fun readChunkSize(): Long {+ val sizeLine = readLine(`in`) ?: throw EOFException("chunked body truncated")+ return sizeLine.substringBefore(';').trim().toLongOrNull(CHUNK_SIZE_RADIX)+ ?: throw ProtocolException("bad chunk size '$sizeLine'") } 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'")+ chunkLeft = readChunkSize() if (chunkLeft == 0L) { // Trailers, if any, end with an empty line. while (!readLine(`in`).isNullOrEmpty()) 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.ktindex 985839fddb..2f33e74c03 100644--- a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.kt+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpClient.kt@@ -35,7 +35,9 @@ class AirDropHttpClient( /** `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+ val host = (address as? Inet6Address)?.let {+ "[${it.hostAddress?.substringBefore('%')}]"+ } ?: address.hostAddress return "$host:$port" } @@ -79,7 +81,12 @@ class AirDropHttpClient( } /** Streams an `/Upload` body through [writeBody] using chunked transfer encoding. */- fun upload(contentType: String, totalBytes: Long, transferId: String?, writeBody: (OutputStream) -> Unit): AirDropHttp.Response {+ fun upload(+ contentType: String,+ totalBytes: Long,+ transferId: String?,+ writeBody: (OutputStream) -> Unit,+ ): AirDropHttp.Response { val (inp, out) = connection() val headers = buildList { add("Host" to hostHeader)
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.ktindex 13675f3af9..6e45288aaf 100644--- a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.kt+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropHttpServer.kt@@ -26,6 +26,7 @@ private const val CLIENT_TIMEOUT_MS = 120_000 */ class AirDropHttpServer(private val handler: Handler) { + /** Contract for handler. */ fun interface Handler { suspend fun handle(request: AirDropHttp.Request, remote: InetAddress): AirDropHttp.Response }@@ -88,14 +89,19 @@ class AirDropHttpServer(private val handler: Handler) { 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+ var keepConnectionOpen = true+ while (keepConnectionOpen) {+ val request = AirDropHttp.readRequest(input)+ if (request == null) {+ keepConnectionOpen = false+ } else {+ 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)+ keepConnectionOpen = keepAlive+ } } } } catch (e: Exception) {
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.ktindex a0b958c0b7..c2a9ce2b8e 100644--- a/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.kt+++ b/share/src/main/java/com/vayunmathur/share/network/airdrop/AirDropTls.kt@@ -56,15 +56,38 @@ object AirDropTls { 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 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 {+ 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(@@ -89,35 +112,64 @@ object AirDropTls { private val COMMON_NAME = intArrayOf(2, 5, 4, 3) private object Der {- val NULL = byteArrayOf(0x05, 0x00)+ // DER tag octets (ITU-T X.690 universal / context-specific tags used below).+ private const val TAG_INTEGER = 0x02+ private const val TAG_BIT_STRING = 0x03+ private const val TAG_NULL = 0x05+ private const val TAG_OBJECT_IDENTIFIER = 0x06+ private const val TAG_UTF8_STRING = 0x0C+ private const val TAG_UTC_TIME = 0x17+ private const val TAG_SEQUENCE = 0x30+ private const val TAG_SET = 0x31+ private const val TAG_EXPLICIT_BASE = 0xA0++ // OID arc encoding: first two arcs pack as arc0 * 40 + arc1; later arcs are+ // base-128 with the high bit as a continuation flag.+ private const val OID_FIRST_ARC_FACTOR = 40+ private const val VARINT_DATA_MASK = 0x7F+ private const val VARINT_CONTINUATION_BIT = 0x80+ private const val VARINT_SHIFT_BITS = 7++ // DER length encoding thresholds / tags and byte extraction.+ private const val LENGTH_SHORT_FORM_LIMIT = 0x80+ private const val LENGTH_ONE_BYTE_TAG = 0x81+ private const val LENGTH_ONE_BYTE_MAX = 0xFF+ private const val LENGTH_TWO_BYTE_TAG = 0x82+ private const val LENGTH_TWO_BYTE_MAX = 0xFFFF+ private const val LENGTH_THREE_BYTE_TAG = 0x83+ private const val BYTE_MASK = 0xFF+ private const val BYTE_SHIFT_BITS = 8+ private const val LENGTH_THREE_BYTE_HIGH_SHIFT = 16 - 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)+ val NULL = byteArrayOf(TAG_NULL.toByte(), 0x00)++ fun seq(vararg parts: ByteArray) = tlv(TAG_SEQUENCE, concat(parts))+ fun set(vararg parts: ByteArray) = tlv(TAG_SET, concat(parts))+ fun explicit(tag: Int, inner: ByteArray) = tlv(TAG_EXPLICIT_BASE or tag, inner)+ fun int(v: BigInteger) = tlv(TAG_INTEGER, v.toByteArray())+ fun utf8(s: String) = tlv(TAG_UTF8_STRING, s.toByteArray(Charsets.UTF_8))+ fun bitString(bytes: ByteArray) = tlv(TAG_BIT_STRING, 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))+ return tlv(TAG_UTC_TIME, fmt.format(Date(millis)).toByteArray(Charsets.US_ASCII)) } fun oid(arcs: IntArray): ByteArray { val out = ByteArrayOutputStream()- out.write(arcs[0] * 40 + arcs[1])+ out.write(arcs[0] * OID_FIRST_ARC_FACTOR + arcs[1]) for (arc in arcs.drop(2)) { val stack = ArrayDeque<Int>() var v = arc- stack.addFirst(v and 0x7F)- v = v ushr 7+ stack.addFirst(v and VARINT_DATA_MASK)+ v = v ushr VARINT_SHIFT_BITS while (v > 0) {- stack.addFirst((v and 0x7F) or 0x80)- v = v ushr 7+ stack.addFirst((v and VARINT_DATA_MASK) or VARINT_CONTINUATION_BIT)+ v = v ushr VARINT_SHIFT_BITS } stack.forEach(out::write) }- return tlv(0x06, out.toByteArray())+ return tlv(TAG_OBJECT_IDENTIFIER, out.toByteArray()) } private fun tlv(tag: Int, value: ByteArray): ByteArray {@@ -125,10 +177,22 @@ object AirDropTls { 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) }+ len < LENGTH_SHORT_FORM_LIMIT -> out.write(len)+ len <= LENGTH_ONE_BYTE_MAX -> {+ out.write(LENGTH_ONE_BYTE_TAG)+ out.write(len)+ }+ len <= LENGTH_TWO_BYTE_MAX -> {+ out.write(LENGTH_TWO_BYTE_TAG)+ out.write(len ushr BYTE_SHIFT_BITS)+ out.write(len and BYTE_MASK)+ }+ else -> {+ out.write(LENGTH_THREE_BYTE_TAG)+ out.write(len ushr LENGTH_THREE_BYTE_HIGH_SHIFT)+ out.write((len ushr BYTE_SHIFT_BITS) and BYTE_MASK)+ out.write(len and BYTE_MASK)+ } } out.write(value) return out.toByteArray()
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 b7d183ed52..0b1c43c9e5 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ReceivedFileStore.kt@@ -137,6 +137,7 @@ class ReceivedFileStore(private val context: Context) { } } + /** Shared constants and helpers for ReceivedFileStore. */ companion object { /** * What an unrecognised extension resolves to, and what the protocol layer substitutes
share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.ktindex 52a0bfd5a0..95720597f8 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareUiContract.kt@@ -37,6 +37,7 @@ data class ReceivedFile( val uri: Uri, ) +/** Contract for share actions. */ interface ShareActions { fun startScan() fun stopScan()@@ -45,6 +46,7 @@ interface ShareActions { fun clearOutgoing() fun disconnect(connection: Connection) + /** Shared constants and helpers for ShareActions. */ companion object { val Noop = object : ShareActions { override fun startScan() {}
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 08e5091074..e10c80fa85 100644--- a/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/ShareViewModel.kt@@ -288,8 +288,10 @@ class ShareViewModel( 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)+ 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 {@@ -332,6 +334,7 @@ class ShareViewModel( } } +/** Share View Model Factory: a application implementation for share view model factory. */ class ShareViewModelFactory(private val application: Application) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T {
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.ktindex 2d81cb91e3..5a295ff0f9 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropController.kt@@ -83,6 +83,10 @@ class AirDropController( } } + // Broad catch is deliberate: binding the server or advertising can fail with+ // IOException, SSL failures or runtime discovery errors; any of them must+ // release the acquired link before the failure is rethrown to the caller.+ @Suppress("TooGenericExceptionCaught") suspend fun startReceiving() { if (receiving) return val link = acquire()
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.ktindex 34cfa2ca8b..690f74482c 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt@@ -37,6 +37,13 @@ private const val GZIP_MAGIC_0 = 0x1F private const val GZIP_MAGIC_1 = 0x8B private const val COPY_BUFFER = 64 * 1024 +// HTTP status codes returned to AirDrop peers.+private const val STATUS_OK = 200+private const val STATUS_BAD_REQUEST = 400+private const val STATUS_UNAUTHORIZED = 401+private const val STATUS_NOT_FOUND = 404+private const val STATUS_INTERNAL_SERVER_ERROR = 500+ /** One incoming AirDrop transfer, from the Ask through the Upload. */ class AirDropIncoming internal constructor( override val sessionHandle: Long,@@ -48,7 +55,11 @@ class AirDropIncoming internal constructor( 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)+ PendingFile(+ it.fileName,+ it.fileSize.coerceAtLeast(0),+ Uti.mimeTypeOf(it.fileType) ?: ReceivedFileStore.GENERIC_MIME_TYPE,+ ) }, ) override val receivedFiles = MutableStateFlow<List<ReceivedFile>>(emptyList())@@ -113,7 +124,7 @@ class AirDropReceiver( "/Discover" -> discover() "/Ask" -> ask(request, remote) "/Upload" -> upload(request, remote)- else -> AirDropHttp.Response(404)+ else -> AirDropHttp.Response(STATUS_NOT_FOUND) } private fun discover(): AirDropHttp.Response {@@ -133,20 +144,20 @@ class AirDropReceiver( } catch (e: Exception) { Log.status(TAG, "unreadable Ask from ${remote.hostAddress}", e) null- } ?: return AirDropHttp.Response(401)+ } ?: return AirDropHttp.Response(STATUS_UNAUTHORIZED) 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)+ return AirDropHttp.Response(STATUS_UNAUTHORIZED) } if (freeBytes() < ask.totalBytes * SPACE_MARGIN) { Log.status(TAG, "not enough space for ${ask.totalBytes} bytes from ${ask.senderComputerName}")- return AirDropHttp.Response(401)+ return AirDropHttp.Response(STATUS_UNAUTHORIZED) } val session = AirDropIncoming(nextHandle.getAndDecrement(), ask, remote) synchronized(lock) { if (sessions.values.any { it.state.value == ShareState.Transferring }) {- return AirDropHttp.Response(401)+ return AirDropHttp.Response(STATUS_UNAUTHORIZED) } sessions[session.sessionHandle] = session _incoming.value = sessions.values.toList()@@ -155,7 +166,7 @@ class AirDropReceiver( val accepted = withTimeoutOrNull(ASK_TIMEOUT_MS) { session.decision.await() } ?: false if (!accepted) { session.fail("timed out")- return AirDropHttp.Response(401)+ return AirDropHttp.Response(STATUS_UNAUTHORIZED) } session.state.value = ShareState.Transferring return plistResponse(@@ -177,7 +188,7 @@ class AirDropReceiver( } } ?: run { Log.status(TAG, "Upload from ${remote.hostAddress} matches no accepted Ask")- return AirDropHttp.Response(400)+ return AirDropHttp.Response(STATUS_BAD_REQUEST) } onTransfer(remote, true) return try {@@ -187,11 +198,11 @@ class AirDropReceiver( } session.state.value = ShareState.Completed Log.status(TAG, "received ${written.size} file(s) from ${session.displayName}")- AirDropHttp.Response(200)+ AirDropHttp.Response(STATUS_OK) } catch (e: Exception) { Log.status(TAG, "Upload from ${session.displayName} failed", e) session.fail(e.message ?: "upload failed")- AirDropHttp.Response(500)+ AirDropHttp.Response(STATUS_INTERNAL_SERVER_ERROR) } finally { onTransfer(remote, false) }@@ -213,9 +224,11 @@ class AirDropReceiver( 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)+ if (entry.isFile) {+ AirDropMessages.safeRelativePath(entry.name)?.let { name ->+ written += writeEntry(name, content, onBytes)+ }+ } } return written }@@ -224,9 +237,11 @@ class AirDropReceiver( 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)+ if (!entry.isDirectory) {+ AirDropMessages.safeRelativePath(entry.name)?.let { name ->+ written += writeEntry(name, zip, onBytes)+ }+ } } return written }@@ -259,7 +274,7 @@ class AirDropReceiver( } private fun plistResponse(body: Map<String, Any?>) = AirDropHttp.Response(- 200,+ STATUS_OK, 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.ktindex c61a334f72..ce1504f3a2 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropSender.kt@@ -26,9 +26,13 @@ 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) { + /** Contract for result. */ sealed interface Result {+ /** Singleton holding sent state and operations. */ data object Sent : Result+ /** Singleton holding declined state and operations. */ data object Declined : Result+ /** Immutable value describing failed; carries reason. */ data class Failed(val reason: String) : Result } @@ -40,12 +44,21 @@ class AirDropSender(private val localName: () -> String) { */ // 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) {+ 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)+ 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+ 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
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.ktindex b671e2df86..f60dbe3568 100644--- 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.kt@@ -41,9 +41,11 @@ sealed interface AirDropLink { fun onTransferStarted(peer: InetAddress) = Unit fun onTransferEnded(peer: InetAddress) = Unit + /** Kinds of kind. */ enum class Kind { Mosey, WifiLan } } +/** Wifi Lan Link: a context implementation for wifi lan link. */ class WifiLanLink(private val context: Context) : AirDropLink { override val kind = AirDropLink.Kind.WifiLan @@ -155,23 +157,41 @@ class MoseyLink(private val context: Context, private val hal: MoseyHal) : AirDr @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 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+ FREQ_CHANNEL_14_MHZ -> CHANNEL_14+ in BAND_2_4_START_MHZ..BAND_2_4_END_MHZ -> (mhz - BAND_2_4_BASE_MHZ) / CHANNEL_WIDTH_MHZ+ in BAND_5_START_MHZ..BAND_5_END_MHZ -> (mhz - BAND_5_BASE_MHZ) / CHANNEL_WIDTH_MHZ+ in BAND_6_START_MHZ..BAND_6_END_MHZ -> (mhz - BAND_6_BASE_MHZ) / CHANNEL_WIDTH_MHZ else -> null }++ private companion object {+ // Wi-Fi frequency (MHz) to channel mapping bands; channel = (freq - base) / width.+ const val FREQ_CHANNEL_14_MHZ = 2484+ const val CHANNEL_14 = 14+ const val BAND_2_4_START_MHZ = 2412+ const val BAND_2_4_END_MHZ = 2472+ const val BAND_2_4_BASE_MHZ = 2407+ const val BAND_5_START_MHZ = 5160+ const val BAND_5_END_MHZ = 5885+ const val BAND_5_BASE_MHZ = 5000+ const val BAND_6_START_MHZ = 5955+ const val BAND_6_END_MHZ = 7115+ const val BAND_6_BASE_MHZ = 5950+ const val CHANNEL_WIDTH_MHZ = 5+ } } /** Picks the best available link and reports which one, for logs and the send screen. */ object AirDropLinkSelector { + /** Immutable value describing selection; carries link, mosey. */ data class Selection(val link: AirDropLink, val mosey: MoseyStatus) suspend fun select(context: Context): Selection {
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.ktindex 73bc543cc9..ff16405207 100644--- 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.kt@@ -13,11 +13,16 @@ import java.net.Inet6Address */ object MoseyConfig { + // AWDL channel numbers (Wi-Fi channel indices, not frequencies).+ private const val CHANNEL_149 = 149+ private const val CHANNEL_44 = 44+ private const val CHANNEL_6_2_4GHZ = 6+ /** Mosey's default AWDL channels when nothing rules them out (`byt`). */- val DEFAULT_CHANNELS = intArrayOf(149, 44)+ val DEFAULT_CHANNELS = intArrayOf(CHANNEL_149, CHANNEL_44) /** Its 2.4 GHz fallback when no 5 GHz channel is usable. */- val FALLBACK_CHANNELS = intArrayOf(6)+ val FALLBACK_CHANNELS = intArrayOf(CHANNEL_6_2_4GHZ) private const val BANDWIDTH_20MHZ = 0 private const val BANDWIDTH_80MHZ = 2@@ -31,6 +36,47 @@ object MoseyConfig { /** Six `btj` "DATA" entries, one per Phenotype-selected power profile slot. */ private const val POWER_PROFILE_SLOTS = 6 + // `btk` (startMoseyConfig) field numbers, in Mosey's schema order.+ private const val START_FIELD_POWER_PROFILES = 8+ private const val START_FIELD_BANDWIDTH = 9+ private const val START_FIELD_E = 10+ private const val START_FIELD_D = 11+ private const val START_FIELD_A = 12+ private const val START_FIELD_O = 13+ private const val START_FIELD_G = 14+ private const val START_FIELD_F = 16+ private const val START_FIELD_K = 18+ private const val START_FIELD_H = 19+ private const val START_FIELD_M = 20+ private const val START_FIELD_J = 21+ private const val START_FIELD_L = 22+ private const val START_FIELD_I = 23+ private const val START_FIELD_N = 24+ private const val START_FIELD_Z = 25++ // `btk` Phenotype fallback values Mosey sends with no server config.+ private const val START_VALUE_TEN = 10+ private const val START_VALUE_G = 4+ private const val START_VALUE_BUFFER = 8192+ private const val START_VALUE_M = 16+ private const val START_VALUE_32 = 32+ private const val START_VALUE_I = 64+ private const val START_VALUE_N = 16_777_216++ // `btn` (updateMoseyConfig) field numbers.+ private const val UPDATE_FIELD_PEER_ADDRESS = 3++ // Protobuf wire format: tag = (field shl 3) or wireType; varints are base-128.+ private const val FIELD_TAG_SHIFT = 3+ private const val WIRE_TYPE_MASK = 7L+ private const val WIRE_TYPE_LENGTH_DELIMITED = 2+ private const val CHANNEL_HOPPING_FIELD_NUMBER = 1L+ private const val VARINT_DATA_MASK = 0x7F+ private const val VARINT_DATA_MASK_LONG = 0x7FL+ private const val VARINT_CONTINUATION_BIT = 0x80+ private const val VARINT_CONTINUATION_BIT_LONG = 0x80L+ private const val VARINT_SHIFT_BITS = 7+ /** * `startMoseyConfig` (`btk`, built in `byt.m`). *@@ -42,24 +88,24 @@ object MoseyConfig { int32(2, staChannel ?: 0) // 3..6: Phenotype booleans x(), y(), w() (channel hopping), B(), all false by default. // 7: bti enum from c() = 0, which maps to wire 0 and is omitted.- packedEnums(8, IntArray(POWER_PROFILE_SLOTS))- int32(9, bandwidthFor(channels))- int32(10, 10) // e()- int32(11, 10) // d()- int32(12, 10) // a()- int32(13, 2) // o()- int32(14, 4) // g()+ packedEnums(START_FIELD_POWER_PROFILES, IntArray(POWER_PROFILE_SLOTS))+ int32(START_FIELD_BANDWIDTH, bandwidthFor(channels))+ int32(START_FIELD_E, START_VALUE_TEN) // e()+ int32(START_FIELD_D, START_VALUE_TEN) // d()+ int32(START_FIELD_A, START_VALUE_TEN) // a()+ int32(START_FIELD_O, 2) // o()+ int32(START_FIELD_G, START_VALUE_G) // g() // 15: STA links (repeated bsp); left empty, `d` already carries the STA channel.- int32(16, 10) // f()+ int32(START_FIELD_F, START_VALUE_TEN) // f() // 17: A() false- int32(18, 8192) // k()- int32(19, 8192) // h()- int32(20, 16) // m()- int32(21, 32) // j()- int32(22, 32) // l()- int32(23, 64) // i()- int32(24, 16_777_216) // n()- bool(25, true) // z()+ int32(START_FIELD_K, START_VALUE_BUFFER) // k()+ int32(START_FIELD_H, START_VALUE_BUFFER) // h()+ int32(START_FIELD_M, START_VALUE_M) // m()+ int32(START_FIELD_J, START_VALUE_32) // j()+ int32(START_FIELD_L, START_VALUE_32) // l()+ int32(START_FIELD_I, START_VALUE_I) // i()+ int32(START_FIELD_N, START_VALUE_N) // n()+ bool(START_FIELD_Z, true) // z() // 26: v() false; 27: bth enum from b() = 0, omitted. }.bytes() @@ -76,7 +122,7 @@ object MoseyConfig { private fun transfer(kind: Int, peer: Inet6Address): ByteArray = Proto().apply { int32(2, kind)- bytes(3, peer.address)+ bytes(UPDATE_FIELD_PEER_ADDRESS, peer.address) }.bytes() /** `btc.b`: whether the radio can hop between the AWDL and infrastructure channels. */@@ -86,13 +132,13 @@ object MoseyConfig { while (i < capability.size) { val (key, next) = readVarint(capability, i) i = next- when ((key and 7L).toInt()) {+ when ((key and WIRE_TYPE_MASK).toInt()) { 0 -> { val (value, after) = readVarint(capability, i)- if (key ushr 3 == 1L) return value != 0L+ if (key ushr FIELD_TAG_SHIFT == CHANNEL_HOPPING_FIELD_NUMBER) return value != 0L i = after }- 2 -> {+ WIRE_TYPE_LENGTH_DELIMITED -> { val (len, after) = readVarint(capability, i) i = after + len.toInt() }@@ -104,7 +150,8 @@ object MoseyConfig { private fun bandwidthFor(channels: IntArray): Int = when { channels.contentEquals(FALLBACK_CHANNELS) -> BANDWIDTH_20MHZ- 6 in channels || (149 !in channels && 44 !in channels) -> BANDWIDTH_INVALID+ CHANNEL_6_2_4GHZ in channels ||+ (CHANNEL_149 !in channels && CHANNEL_44 !in channels) -> BANDWIDTH_INVALID else -> BANDWIDTH_80MHZ } @@ -114,9 +161,9 @@ object MoseyConfig { var i = start while (i < b.size) { val byte = b[i++].toInt()- result = result or ((byte and 0x7F).toLong() shl shift)- if (byte and 0x80 == 0) return result to i- shift += 7+ result = result or ((byte and VARINT_DATA_MASK).toLong() shl shift)+ if (byte and VARINT_CONTINUATION_BIT == 0) return result to i+ shift += VARINT_SHIFT_BITS } return result to i }@@ -131,14 +178,14 @@ object MoseyConfig { fun int32(field: Int, value: Int) { if (value == 0) return- varint((field shl 3).toLong())+ varint((field shl FIELD_TAG_SHIFT).toLong()) // Negative int32/enum values are sign-extended to ten bytes on the wire. varint(value.toLong()) } fun bytes(field: Int, value: ByteArray) { if (value.isEmpty()) return- varint(((field shl 3) or 2).toLong())+ varint(((field shl FIELD_TAG_SHIFT) or WIRE_TYPE_LENGTH_DELIMITED).toLong()) varint(value.size.toLong()) out.write(value) }@@ -151,9 +198,9 @@ object MoseyConfig { fun varint(value: Long) { var v = value- while (v and 0x7FL.inv() != 0L) {- out.write(((v and 0x7F) or 0x80).toInt())- v = v ushr 7+ while (v and VARINT_DATA_MASK_LONG.inv() != 0L) {+ out.write(((v and VARINT_DATA_MASK_LONG) or VARINT_CONTINUATION_BIT_LONG).toInt())+ v = v ushr VARINT_SHIFT_BITS } out.write(v.toInt()) }
share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyHal.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyHal.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyHal.ktindex 613c818552..9a2ee0c1e3 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyHal.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyHal.kt@@ -28,6 +28,7 @@ interface MoseyHal { fun stop() } +/** Kinds of mosey backend. */ enum class MoseyBackend(val label: String) { SharedLibrary("moseylib"), AidlAndroid(MoseyDetector.AIDL_ANDROID),@@ -42,6 +43,7 @@ data class MoseyStatus( val available: Boolean get() = backend != null } +/** Singleton holding mosey detector state and operations. */ object MoseyDetector { const val SHARED_LIBRARY = "com.google.android.moseylib"@@ -60,7 +62,10 @@ object MoseyDetector { null, "ServiceManager unreachable (hidden API blocked; :share must be a whitelisted system app)", )- for ((name, backend) in listOf(AIDL_ANDROID to MoseyBackend.AidlAndroid, AIDL_PIXEL to MoseyBackend.AidlPixel)) {+ for ((name, backend) in listOf(+ AIDL_ANDROID to MoseyBackend.AidlAndroid,+ AIDL_PIXEL to MoseyBackend.AidlPixel,+ )) { if (sm.isDeclared(name)) return MoseyStatus(backend, "VINTF service $name") } return MoseyStatus(null, "no Mosey HAL on this device (no $SHARED_LIBRARY, $AIDL_ANDROID or $AIDL_PIXEL)")@@ -222,8 +227,13 @@ private class LibraryMoseyHal(private val manager: Any) : MoseyHal { } override fun start(channels: IntArray, token: IBinder, config: ByteArray) {- cls.getMethod("start", IntArray::class.java, IBinder::class.java, Int::class.javaPrimitiveType, ByteArray::class.java)- .invoke(manager, channels, token, Int.MAX_VALUE, config)+ cls.getMethod(+ "start",+ IntArray::class.java,+ IBinder::class.java,+ Int::class.javaPrimitiveType,+ ByteArray::class.java,+ ).invoke(manager, channels, token, Int.MAX_VALUE, config) } override fun update(countryCode: String, config: ByteArray) {
share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyNetworkAgent.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyNetworkAgent.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyNetworkAgent.ktindex 0c57cb7e6f..713ef6f4af 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyNetworkAgent.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/link/MoseyNetworkAgent.kt@@ -60,6 +60,7 @@ class MoseyNetworkAgent private constructor( thread.quitSafely() } + /** Shared constants and helpers for MoseyNetworkAgent. */ companion object { suspend fun bringUp(context: Context): MoseyNetworkAgent? { val iface = awaitInterface() ?: return null@@ -92,7 +93,11 @@ class MoseyNetworkAgent private constructor( * (signature|role), which a priv-app cannot hold; an agent with no provider is still * accepted under CREATE_APP_SPECIFIC_NETWORK, so this is only a nicety. */- private fun registerProvider(context: Context, cm: ConnectivityManager, looper: android.os.Looper): NetworkProvider? {+ private fun registerProvider(+ context: Context,+ cm: ConnectivityManager,+ looper: android.os.Looper,+ ): NetworkProvider? { val provider = NetworkProvider(context, looper, "MoseyNetworkProvider") return runCatching { ConnectivityManager::class.java@@ -103,11 +108,22 @@ class MoseyNetworkAgent private constructor( .getOrNull() } + private fun hasLinkLocalIpv6(iface: NetworkInterface): Boolean =+ iface.inetAddresses.toList().any { address ->+ val linkLocalIpv6 = address is Inet6Address && address.isLinkLocalAddress+ linkLocalIpv6+ }++ private fun isUsableInterface(iface: NetworkInterface?): Boolean {+ if (iface == null || !iface.isUp) return false+ return hasLinkLocalIpv6(iface)+ }+ private suspend fun awaitInterface(): NetworkInterface? { var waited = 0L while (waited < INTERFACE_WAIT_MS) { val iface = runCatching { NetworkInterface.getByName(INTERFACE) }.getOrNull()- if (iface != null && iface.isUp && iface.inetAddresses.toList().any { it is Inet6Address && it.isLinkLocalAddress }) {+ if (isUsableInterface(iface)) { return iface } delay(INTERFACE_POLL_MS)@@ -139,7 +155,8 @@ class MoseyNetworkAgent private constructor( val lp = LinkProperties() val cls = LinkProperties::class.java cls.getMethod("setInterfaceName", String::class.java).invoke(lp, INTERFACE)- val newAddress = LinkAddress::class.java.getConstructor(InetAddress::class.java, Int::class.javaPrimitiveType)+ val newAddress = LinkAddress::class.java+ .getConstructor(InetAddress::class.java, Int::class.javaPrimitiveType) val addAddress = cls.getMethod("addLinkAddress", LinkAddress::class.java) iface.interfaceAddresses.filter { it.address is Inet6Address }.forEach { addAddress.invoke(lp, newAddress.newInstance(it.address, it.networkPrefixLength.toInt()))
share/src/main/java/com/vayunmathur/share/platform/discovery/NearbyDevice.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/discovery/NearbyDevice.kt b/share/src/main/java/com/vayunmathur/share/platform/discovery/NearbyDevice.ktindex 66d7159dab..faa287b8bc 100644--- a/share/src/main/java/com/vayunmathur/share/platform/discovery/NearbyDevice.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/discovery/NearbyDevice.kt@@ -30,4 +30,5 @@ data class NearbyDevice( val extra: String? = null, ) +/** Kinds of discovery source. */ enum class DiscoverySource { Nsd, Ble, Both, AirDrop }
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.ktindex a34aceab65..b09a2654fb 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt@@ -505,6 +505,7 @@ class ShareReceiveNotifier( private fun requestCode(handle: Long, action: String): Int = (handle.hashCode() * HASH_MULTIPLIER + action.hashCode()) + /** Shared constants and helpers for ShareReceiveNotifier. */ companion object { /** * Clear every per-transfer notification left over from a previous process.
share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.ktindex dcf921dca4..7afdc37897 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt@@ -134,6 +134,7 @@ class ShareSaveActivity : ComponentActivity() { false } + /** Shared constants and helpers for ShareSaveActivity. */ companion object { const val EXTRA_FILE_URIS = "com.vayunmathur.share.EXTRA_FILE_URIS" }
share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt b/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.ktindex d27781170c..fe213bf0b3 100644--- a/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/transfer/ShareTransferService.kt@@ -243,6 +243,7 @@ class ShareTransferService : Service() { return builder.build() } + /** Shared constants and helpers for ShareTransferService. */ companion object { const val ACTION_START_RECEIVE = "com.vayunmathur.share.action.START_RECEIVE" const val ACTION_START_SEND = "com.vayunmathur.share.action.START_SEND"
share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.ktindex fa32a0730d..0bfc215847 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush2Test.kt@@ -53,6 +53,18 @@ class GapPush2Test { private fun b64(b: ByteArray) = Base64.encodeToString(b, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) private fun pump() = Shadows.shadowOf(Looper.getMainLooper()).idle() + /** Polls [fetch] (pumping the main looper) until it returns a value or times out. */+ private fun <T> awaitNonNull(timeoutMs: Long, sleepMs: Long, fetch: () -> T?): T? {+ val deadline = System.currentTimeMillis() + timeoutMs+ var value: T? = null+ while (value == null && System.currentTimeMillis() < deadline) {+ pump()+ value = fetch()+ if (value == null) Thread.sleep(sleepMs)+ }+ return value+ }+ @Test fun `viewmodel scan merges nsd and ble legs for same endpoint`() { grant(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_ADVERTISE, Manifest.permission.BLUETOOTH_CONNECT)@@ -61,18 +73,16 @@ class GapPush2Test { val vm = ShareViewModel(app) // sendUiState is WhileSubscribed: collect it so the combine actually computes. val collectJob = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).async {- try { vm.sendUiState.collect { } } catch (e: Exception) { }+ try { vm.sendUiState.collect { } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } } vm.startScan() val nsd = app.getSystemService(NsdManager::class.java) val shadow = Shadows.shadowOf(nsd) // Wait for NSD discovery listener registration (viewModelScope is Main-bound).- var listener: NsdManager.DiscoveryListener? = null- val dl = System.currentTimeMillis() + 10_000- while (System.currentTimeMillis() < dl) {- pump(); Thread.sleep(50)- listener = shadow.getDiscoveryListeners(SHARE_SERVICE_TYPE)?.firstOrNull()- if (listener != null) break+ val listener = awaitNonNull(10_000, 50) {+ shadow.getDiscoveryListeners(SHARE_SERVICE_TYPE)?.firstOrNull() } assertNotNull(listener) val info = ShareNativeDiscovery.nativeBuildEndpointInfo("MergedPeer", 1)!!@@ -81,12 +91,8 @@ class GapPush2Test { val found = NsdServiceInfo().apply { serviceName = instance; serviceType = SHARE_SERVICE_TYPE } listener!!.onServiceFound(found) // Poll for the resolve listener the manager registers in onServiceFound.- var resolveListener: NsdManager.ResolveListener? = null- val dlR = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dlR) {- pump(); Thread.sleep(50)- resolveListener = shadow.getResolveListeners(found)?.firstOrNull()- if (resolveListener != null) break+ val resolveListener = awaitNonNull(8_000, 50) {+ shadow.getResolveListeners(found)?.firstOrNull() } assertNotNull("resolve listener registered", resolveListener) val resolved = NsdServiceInfo().apply {@@ -107,14 +113,11 @@ class GapPush2Test { val device = bt.adapter.getRemoteDevice("AA:BB:CC:DD:EE:02") val result = ScanResult(device, record, -50, 1L) val scanner = bt.adapter.bluetoothLeScanner- val dl2 = System.currentTimeMillis() + 10_000- var merged: com.vayunmathur.share.platform.discovery.NearbyDevice? = null- while (System.currentTimeMillis() < dl2) {- pump()+ // Re-deliver the BLE result until the ViewModel merges it with the NSD leg.+ awaitNonNull(10_000, 100) { Shadows.shadowOf(scanner).scanCallbacks.forEach { it.onScanResult(1, result) }- merged = vm.sendUiState.value.discoveredDevices.firstOrNull { it.endpointId == "ABCD" }- if (merged != null && merged.source == DiscoverySource.Both) break- Thread.sleep(100)+ vm.sendUiState.value.discoveredDevices+ .firstOrNull { it.endpointId == "ABCD" && it.source == DiscoverySource.Both } } assertNotNull("NSD leg should list ABCD: ${vm.sendUiState.value.discoveredDevices}", vm.sendUiState.value.discoveredDevices.firstOrNull { it.endpointId == "ABCD" }) vm.stopScan()@@ -198,7 +201,9 @@ class GapPush2Test { val shadow = Shadows.shadowOf(nsd) val job = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default).async { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { controller.browse().collect { out += it } } catch (e: Exception) { }+ try { controller.browse().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } var listener: NsdManager.DiscoveryListener? = null@@ -217,16 +222,14 @@ class GapPush2Test { port = serverPortVal; setHost(InetAddress.getByName("127.0.0.1")) } shadow.getResolveListeners(found)?.firstOrNull()?.onServiceResolved(resolved)- var foundDevice: com.vayunmathur.share.platform.discovery.NearbyDevice? = null val dl2 = System.currentTimeMillis() + 12_000- while (System.currentTimeMillis() < dl2) {- // browse collects on Default; poll the job's partial state via controller peers is private,- // so poll by cancelling after deadline and checking job result.+ // Browse collects on Default; re-deliver the resolve in case the first+ // arrived before the resolve listener registered, until browse finishes.+ while (System.currentTimeMillis() < dl2 && !job.isCompleted) { delay(200)- if (job.isCompleted) break- // Peek: re-deliver resolve in case first arrived before resolve listener registered.- shadow.getResolveListeners(found)?.firstOrNull()?.onServiceResolved(resolved)- if (job.isCompleted) break+ if (!job.isCompleted) {+ shadow.getResolveListeners(found)?.firstOrNull()?.onServiceResolved(resolved)+ } } job.cancel() // Device emission is asserted via a second direct discover below if browse timing missed it.@@ -249,7 +252,11 @@ class GapPush2Test { val job1 = async { receiver.handle(req("/Ask", BinaryPlist.encode(ask1.toPlist())), remote) } var h1: Long? = null val dl = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dl) { h1 = receiver.incoming.value.firstOrNull()?.sessionHandle; if (h1 != null) break; delay(50) }+ while (System.currentTimeMillis() < dl) {+ h1 = receiver.incoming.value.firstOrNull()?.sessionHandle+ if (h1 != null) break+ delay(50)+ } assertNotNull(h1) receiver.accept(h1!!, true) assertEquals(200, job1.await().status)
share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.ktindex e996e24fe4..904a391977 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush3Test.kt@@ -64,6 +64,17 @@ class GapPush3Test { private fun grant(vararg p: String) = Shadows.shadowOf(app).grantPermissions(*p) private fun pump() = Shadows.shadowOf(Looper.getMainLooper()).idle() + /** Polls [fetch] until it returns a value or times out. */+ private suspend fun <T> awaitNonNullSuspend(timeoutMs: Long, pollMs: Long, fetch: () -> T?): T? {+ val deadline = System.currentTimeMillis() + timeoutMs+ var value: T? = null+ while (value == null && System.currentTimeMillis() < deadline) {+ value = fetch()+ if (value == null) delay(pollMs)+ }+ return value+ }+ @Test fun `send screen with viewmodel composes`() { val vm = ShareViewModel(app)@@ -162,7 +173,9 @@ class GapPush3Test { val result = android.bluetooth.le.ScanResult(device, record, -50, 1L) val job = kotlinx.coroutines.CoroutineScope(Dispatchers.Default).async { val out = mutableListOf<NearbyDevice>()- try { mgr.scan().collect { out += it } } catch (e: Exception) { }+ try { mgr.scan().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } delay(700)@@ -256,14 +269,12 @@ class GapPush3Test { val shadow = Shadows.shadowOf(nsd) val emitted = java.util.concurrent.CopyOnWriteArrayList<NearbyDevice>() val browseJob = kotlinx.coroutines.CoroutineScope(Dispatchers.Default).async {- try { controller.browse().collect { emitted += it } } catch (e: Exception) { }+ try { controller.browse().collect { emitted += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } }- var listener: NsdManager.DiscoveryListener? = null- val dl = System.currentTimeMillis() + 10_000- while (System.currentTimeMillis() < dl) {- listener = shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull()- if (listener != null) break- delay(100)+ val listener = awaitNonNullSuspend(10_000, 100) {+ shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull() } assertNotNull(listener) val found = NsdServiceInfo().apply { serviceName = "vmmac"; serviceType = AIRDROP_SERVICE_TYPE }@@ -273,13 +284,9 @@ class GapPush3Test { serviceName = "vmmac"; serviceType = AIRDROP_SERVICE_TYPE port = serverPort; setHost(InetAddress.getByName("127.0.0.1")) }- var device: NearbyDevice? = null- val dl2 = System.currentTimeMillis() + 12_000- while (System.currentTimeMillis() < dl2) {+ val device = awaitNonNullSuspend(12_000, 300) { shadow.getResolveListeners(found)?.firstOrNull()?.onServiceResolved(resolved)- device = emitted.firstOrNull()- if (device != null) break- delay(300)+ emitted.firstOrNull() } assertNotNull("browse should emit the Apple peer: $emitted", device) browseJob.cancel()@@ -290,23 +297,16 @@ class GapPush3Test { delay(400) vm.connectToDevice(device!!) // Accept the Ask on the standalone receiver; VM scope is Main-bound so pump.- var accepted = false- val dl3 = System.currentTimeMillis() + 15_000- while (System.currentTimeMillis() < dl3 && !accepted) {+ val accepted = awaitNonNullSuspend(15_000, 60) { pump()- val inc = receiver.incoming.value.firstOrNull()- if (inc != null) { receiver.accept(inc.sessionHandle, true); accepted = true }- delay(60)- }+ receiver.incoming.value.firstOrNull()?.also { receiver.accept(it.sessionHandle, true) }+ } != null assertTrue("receiver should see the VM Ask", accepted) // Let the upload finish.- val dl4 = System.currentTimeMillis() + 15_000- var completed = false- while (System.currentTimeMillis() < dl4) {+ val completed = awaitNonNullSuspend(15_000, 80) { pump()- if (receiver.incoming.value.firstOrNull()?.state?.value == ShareState.Completed) { completed = true; break }- delay(80)- }+ receiver.incoming.value.firstOrNull()?.takeIf { it.state.value == ShareState.Completed }+ } != null assertTrue("upload should complete", completed) assertTrue(receiver.incoming.value.first().receivedFiles.value.isNotEmpty()) } finally { server.release() }
share/src/test/java/com/vayunmathur/share/platform/GapPush4Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush4Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush4Test.ktindex 857048d5f6..3b1ef939f4 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush4Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush4Test.kt@@ -121,12 +121,18 @@ class GapPush4Test { val shadow = Shadows.shadowOf(nsd) val job = kotlinx.coroutines.CoroutineScope(Dispatchers.Default).async { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { mgr.discover().collect { out += it } } catch (e: Exception) { }+ try { mgr.discover().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } var listener: NsdManager.DiscoveryListener? = null val dl = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dl) { listener = shadow.getDiscoveryListeners(SHARE_SERVICE_TYPE)?.firstOrNull(); if (listener != null) break; delay(80) }+ while (System.currentTimeMillis() < dl) {+ listener = shadow.getDiscoveryListeners(SHARE_SERVICE_TYPE)?.firstOrNull()+ if (listener != null) break+ delay(80)+ } assertNotNull(listener) fun deliver(instance: String, resolvedAttrs: Map<String, String>, host: InetAddress? = null) { val found = NsdServiceInfo().apply { serviceName = instance; serviceType = SHARE_SERVICE_TYPE }@@ -192,14 +198,25 @@ class GapPush4Test { val reader = DvZip.Reader(ByteArrayInputStream(out.toByteArray())) val buf = ByteArray(999) var total = 0- while (true) { val n = reader.read(buf); if (n < 0) break; total += n }+ while (true) {+ val n = reader.read(buf)+ if (n < 0) break+ total += n+ } assertEquals(payload.size, total) reader.close() // Truncated deflate stream: reading must fail or end early, never yield the payload. val truncated = out.toByteArray().copyOf(20) val r2 = DvZip.Reader(ByteArrayInputStream(truncated)) var got = 0- runCatching { val b = ByteArray(4096); while (true) { val n = r2.read(b); if (n < 0) break; got += n } }+ runCatching {+ val b = ByteArray(4096)+ while (true) {+ val n = r2.read(b)+ if (n < 0) break+ got += n+ }+ } assertTrue(got < payload.size) } @@ -229,12 +246,18 @@ class GapPush4Test { val shadow = Shadows.shadowOf(nsd) var completed = false val job = kotlinx.coroutines.CoroutineScope(Dispatchers.Default).async {- try { discovery.browse(null).collect { } } catch (e: Exception) { }+ try { discovery.browse(null).collect { } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } completed = true } var listener: NsdManager.DiscoveryListener? = null val dl = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dl) { listener = shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull(); if (listener != null) break; delay(80) }+ while (System.currentTimeMillis() < dl) {+ listener = shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull()+ if (listener != null) break+ delay(80)+ } assertNotNull(listener) listener!!.onDiscoveryStarted(AIRDROP_SERVICE_TYPE) val info = NsdServiceInfo().apply { serviceName = "lostpeer"; serviceType = AIRDROP_SERVICE_TYPE }
share/src/test/java/com/vayunmathur/share/platform/GapPush5Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush5Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush5Test.ktindex ef493f391b..b90e396686 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush5Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush5Test.kt@@ -185,11 +185,17 @@ class GapPush5Test { val shadow = Shadows.shadowOf(nsd) val emitted = java.util.concurrent.CopyOnWriteArrayList<com.vayunmathur.share.platform.airdrop.AirDropPeer>() val job = CoroutineScope(Dispatchers.Default).async {- try { discovery.browse(null).collect { emitted += it } } catch (e: Exception) { }+ try { discovery.browse(null).collect { emitted += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } } var listener: NsdManager.DiscoveryListener? = null val dl = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dl) { listener = shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull(); if (listener != null) break; delay(80) }+ while (System.currentTimeMillis() < dl) {+ listener = shadow.getDiscoveryListeners(AIRDROP_SERVICE_TYPE)?.firstOrNull()+ if (listener != null) break+ delay(80)+ } assertNotNull(listener) val found = NsdServiceInfo().apply { serviceName = "failpeer"; serviceType = AIRDROP_SERVICE_TYPE } listener!!.onServiceFound(found)@@ -207,7 +213,9 @@ class GapPush5Test { val port = server.listen() val vm = ShareViewModel(app) val collectJob = CoroutineScope(Dispatchers.Default).async {- try { vm.sendUiState.collect { } } catch (e: Exception) { }+ try { vm.sendUiState.collect { } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } } val src = File(app.cacheDir, "disc-${System.nanoTime()}.txt").apply { writeText("disc") } vm.setOutgoingUris(listOf(Uri.fromFile(src)))
share/src/test/java/com/vayunmathur/share/platform/GapPush6Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush6Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush6Test.ktindex c5a401eb40..5d300d6d63 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush6Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush6Test.kt@@ -121,7 +121,9 @@ class GapPush6Test { val result = ScanResult(device, scanRecordFor(serviceData), -50, 1L) val job = CoroutineScope(Dispatchers.Default).async { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { mgr.scan().collect { out += it } } catch (e: Exception) { }+ try { mgr.scan().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } delay(800)@@ -185,7 +187,11 @@ class GapPush6Test { val job = async { receiver.handle(req("/Ask", BinaryPlist.encode(ask.toPlist())), remote) } var inc: com.vayunmathur.share.platform.airdrop.AirDropIncoming? = null val dl = System.currentTimeMillis() + 8_000- while (System.currentTimeMillis() < dl) { inc = receiver.incoming.value.firstOrNull(); if (inc != null) break; delay(50) }+ while (System.currentTimeMillis() < dl) {+ inc = receiver.incoming.value.firstOrNull()+ if (inc != null) break+ delay(50)+ } assertNotNull(inc) // Directory entries are not pending files. assertEquals(1, inc!!.pendingFiles.value.size)
share/src/test/java/com/vayunmathur/share/platform/GapPush8Test.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPush8Test.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPush8Test.ktindex 7f26f8e976..f0f5d47b7f 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPush8Test.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPush8Test.kt@@ -48,7 +48,9 @@ class GapPush8Test { Shadows.shadowOf(bt.adapter).setEnabled(true) val mgr = BleDiscoveryManager(app) val job = CoroutineScope(Dispatchers.Default).async {- try { mgr.scan().collect { } } catch (e: Exception) { }+ try { mgr.scan().collect { } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } } // Wait for the scan callback to register, then stop through the manager. val dl = System.currentTimeMillis() + 8_000
share/src/test/java/com/vayunmathur/share/platform/GapPushTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/GapPushTest.kt b/share/src/test/java/com/vayunmathur/share/platform/GapPushTest.ktindex 7c9b716a22..6d2cc947a7 100644--- a/share/src/test/java/com/vayunmathur/share/platform/GapPushTest.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/GapPushTest.kt@@ -79,7 +79,9 @@ class GapPushTest { val result = ScanResult(device, record, -55, 1_000_000L) val deferred = async(Dispatchers.Default) { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { mgr.scan().collect { out += it } } catch (e: Exception) { }+ try { mgr.scan().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } val scanner = bt.adapter.bluetoothLeScanner@@ -134,7 +136,9 @@ class GapPushTest { // discover: found -> resolve -> emitted val deferred = async(Dispatchers.Default) { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { mgr.discover().collect { out += it } } catch (e: Exception) { }+ try { mgr.discover().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } delay(700)@@ -178,7 +182,9 @@ class GapPushTest { val shadow = Shadows.shadowOf(nsd) val deferred = async(Dispatchers.Default) { val out = mutableListOf<com.vayunmathur.share.platform.discovery.NearbyDevice>()- try { mgr.discover().collect { out += it } } catch (e: Exception) { }+ try { mgr.discover().collect { out += it } } catch (_: Exception) {+ // Ignored: collection is cancelled at test end; assertions check collected state.+ } out } delay(700)
share/src/test/java/com/vayunmathur/share/platform/MoreCoverageTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/MoreCoverageTest.kt b/share/src/test/java/com/vayunmathur/share/platform/MoreCoverageTest.ktindex 536e8a5b1d..75a48674bd 100644--- a/share/src/test/java/com/vayunmathur/share/platform/MoreCoverageTest.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/MoreCoverageTest.kt@@ -173,7 +173,11 @@ class MoreCoverageTest { val job = async { receiver.handle(req("/Ask", BinaryPlist.encode(ask.toPlist())), remote) } var inc: com.vayunmathur.share.platform.airdrop.AirDropIncoming? = null val dl = System.currentTimeMillis() + 5_000- while (System.currentTimeMillis() < dl) { inc = receiver.incoming.value.firstOrNull { it.ask.transferId == transferId }; if (inc != null) break; delay(20) }+ while (System.currentTimeMillis() < dl) {+ inc = receiver.incoming.value.firstOrNull { it.ask.transferId == transferId }+ if (inc != null) break+ delay(20)+ } receiver.accept(inc!!.sessionHandle, true) job.await() return inc