Validate LAN events and retain multicast lock ownership on errors
This commit is contained in:
1 parent
22417c5b59
commit
720cc83d01
2 files changed
+138
-46
No files matched your search
@@ -2,20 +2,30 @@ package com.utun.chat.data
|
||||
|
||||
import android.content.Context
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Looper
|
||||
import com.utun.chat.ChatApplication
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.charset.CharacterCodingException
|
||||
|
||||
/** Устройство из открытого LAN-объявления: nodeId хранит все uint64-биты, имя не подтверждает личность.
|
||||
* label — ник и последние до шести hex-цифр ID, только для отображения. */
|
||||
data class LocalDevice(val nodeId: Long, val name: String) {
|
||||
val label: String get() = "$name [${nodeId.toULong().toString(16).takeLast(6)}]"
|
||||
}
|
||||
/** Полученная ссылка, уже проверенная C-кодеком; показ/подключение решает UI, автоматического JOIN нет. */
|
||||
data class LocalInvitation(val device: LocalDevice, val link: String)
|
||||
data class LocalDelivery(val request: Long, val pending: Boolean, val received: Boolean = false, val forbidden: Boolean = false)
|
||||
/** Последняя отправка и снимок адресата; received — ACK приёма ссылки, forbidden — отказ получателя, оба не означают JOIN. */
|
||||
data class LocalDelivery(val request: Long, val device: LocalDevice, val pending: Boolean,
|
||||
val received: Boolean = false, val forbidden: Boolean = false)
|
||||
|
||||
/** Состояние приложения переживает Activity и не повторяет приглашения из replay событий ViewModel.
|
||||
* Все методы вызываются на main; MulticastLock следует эффективной активности native-сервиса. */
|
||||
* Все mutators требуют main, StateFlow можно наблюдать из любого потока. Список устройств заменяется целиком и сортируется по label.
|
||||
* Входящих приглашений не более 8; stop очищает устройства/завершает pending, но сохраняет уже полученные приглашения.
|
||||
* MulticastLock следует native ACTIVE, а не Activity. Ошибка сохраняет владельца lock для следующего сигнала ACTIVE/STOP.
|
||||
* Ссылки/пароли не выводятся в лог. */
|
||||
object LocalDiscovery {
|
||||
private val _devices = MutableStateFlow<List<LocalDevice>>(emptyList())
|
||||
val devices = _devices.asStateFlow()
|
||||
@@ -26,87 +36,156 @@ object LocalDiscovery {
|
||||
private var nextRequest = 0L
|
||||
private var multicastLock: WifiManager.MulticastLock? = null
|
||||
|
||||
/** Одна pending-отправка на приложение; C проверяет ссылку/готовность и асинхронно сообщает результат по request+peer.
|
||||
* Повтор при pending игнорируется с предупреждением; отказ/исключение JNI оставляет терминальное состояние ошибки. */
|
||||
fun send(device: LocalDevice, link: String) {
|
||||
if (_delivery.value?.pending == true) return
|
||||
val request = ++nextRequest
|
||||
_delivery.value = LocalDelivery(request, pending = true)
|
||||
if (!NativeLib.sendLocalInvite(device.nodeId, request, link)) {
|
||||
LogManager.addLog("WARN", "discovery", "invitation enqueue failed peer=${device.nodeId}")
|
||||
_delivery.value = LocalDelivery(request, pending = false)
|
||||
checkMain()
|
||||
_delivery.value?.takeIf { it.pending }?.let {
|
||||
LogManager.addLog("WARN", "discovery", "send ignored: pending request=${it.request} peer=${it.device.nodeId}"); return
|
||||
}
|
||||
nextRequest++
|
||||
if (nextRequest == 0L) nextRequest = 1L
|
||||
val outgoing = LocalDelivery(nextRequest, device, pending = true)
|
||||
_delivery.value = outgoing
|
||||
try {
|
||||
if (!NativeLib.sendLocalInvite(device.nodeId, outgoing.request, link)) {
|
||||
LogManager.addLog("WARN", "discovery", "invitation enqueue failed request=${outgoing.request} peer=${device.nodeId}")
|
||||
_delivery.value = outgoing.copy(pending = false)
|
||||
} else LogManager.addLog("DEBUG", "discovery", "invitation queued request=${outgoing.request} peer=${device.nodeId}")
|
||||
} catch (error: Exception) {
|
||||
// Текст JNI-исключения может содержать ссылку; сохраняем только тип и контекст запроса.
|
||||
LogManager.addLog("ERROR", "discovery", "invitation send failed request=${outgoing.request} peer=${device.nodeId}: ${error.javaClass.simpleName}")
|
||||
_delivery.value = outgoing.copy(pending = false)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearDelivery() { if (_delivery.value?.pending != true) _delivery.value = null }
|
||||
fun dismissInvitation() { _invitations.value = _invitations.value.drop(1) }
|
||||
/** Убрать только терминальный результат; активная отправка продолжает ждать ACK даже при закрытом диалоге. */
|
||||
fun clearDelivery() { checkMain(); if (_delivery.value?.pending != true) _delivery.value = null }
|
||||
/** Убрать старейшее входящее приглашение, не затрагивая native-транспорт/членство. Пустая очередь допустима. */
|
||||
fun dismissInvitation() { checkMain(); _invitations.value = _invitations.value.drop(1) }
|
||||
|
||||
/** События chat_event.h: 61 devices, 62 invite, 63 delivery, 64 active — BE; 13 завершает сервис.
|
||||
* Проверяет полный frame/UTF-8 до изменения состояния; ошибочный frame логируется, прежний снимок сохраняется.
|
||||
* Delivery применяется только к pending с теми же request и peer; старые результаты не возобновляют завершённую отправку. */
|
||||
fun onEvent(type: Int, data: ByteArray?) {
|
||||
checkMain()
|
||||
if (type == 13) {
|
||||
setActive(false); _devices.value = emptyList()
|
||||
_delivery.value?.takeIf { it.pending }?.let { _delivery.value = it.copy(pending = false) }
|
||||
_delivery.value?.takeIf { it.pending }?.let {
|
||||
_delivery.value = it.copy(pending = false)
|
||||
LogManager.addLog("WARN", "discovery", "pending invitation cancelled: core stopped request=${it.request} peer=${it.device.nodeId}")
|
||||
}
|
||||
return
|
||||
}
|
||||
if (type !in 61..64) return invalid(type, data?.size ?: 0, "unsupported event")
|
||||
if (data == null) { LogManager.addLog("WARN", "discovery", "empty event type=$type"); return }
|
||||
val input = ByteBuffer.wrap(data).order(ByteOrder.BIG_ENDIAN)
|
||||
when (type) {
|
||||
try { when (type) {
|
||||
61 -> {
|
||||
if (input.remaining() < 2) return invalid(type, data.size)
|
||||
require(input.remaining() >= 2) { "missing device count" }
|
||||
val count = input.short.toInt() and 0xffff
|
||||
if (count > 128) return invalid(type, data.size)
|
||||
val devices = ArrayList<LocalDevice>(count)
|
||||
repeat(count) {
|
||||
if (input.remaining() < 9) return invalid(type, data.size)
|
||||
val id = input.long
|
||||
val size = input.get().toInt() and 0xff
|
||||
if (size !in 1..127 || input.remaining() < size) return invalid(type, data.size)
|
||||
val name = ByteArray(size).also { input.get(it) }.toString(Charsets.UTF_8)
|
||||
devices.add(LocalDevice(id, name))
|
||||
}
|
||||
if (input.hasRemaining()) return invalid(type, data.size)
|
||||
require(count <= 128) { "invalid device count=$count" }
|
||||
val devices = List(count) { readDevice(input) }
|
||||
require(!input.hasRemaining()) { "trailing device bytes=${input.remaining()}" }
|
||||
require(devices.map { it.nodeId }.toSet().size == count) { "duplicate device IDs" }
|
||||
_devices.value = devices.sortedBy { it.label }
|
||||
LogManager.addLog("DEBUG", "discovery", "device snapshot applied count=$count")
|
||||
}
|
||||
62 -> {
|
||||
if (input.remaining() < 10) return invalid(type, data.size)
|
||||
val id = input.long
|
||||
val size = input.get().toInt() and 0xff
|
||||
if (size !in 1..127 || input.remaining() <= size) return invalid(type, data.size)
|
||||
val name = ByteArray(size).also { input.get(it) }.toString(Charsets.UTF_8)
|
||||
val link = ByteArray(input.remaining()).also { input.get(it) }.toString(Charsets.UTF_8)
|
||||
if (!link.startsWith("utun://")) return invalid(type, data.size)
|
||||
val device = readDevice(input)
|
||||
require(input.remaining() in 1..1100) { "invalid invitation bytes=${input.remaining()}" }
|
||||
val link = readText(input, input.remaining(), "invitation")
|
||||
require(link.startsWith("utun://") && link.length > 7 && '\u0000' !in link) { "invalid invitation prefix/NUL" }
|
||||
if (_invitations.value.size >= 8) {
|
||||
LogManager.addLog("WARN", "discovery", "incoming invitation queue full"); return
|
||||
}
|
||||
_invitations.value += LocalInvitation(LocalDevice(id, name), link)
|
||||
_invitations.value += LocalInvitation(device, link)
|
||||
LogManager.addLog("INFO", "discovery", "invitation received peer=${device.nodeId} queued=${_invitations.value.size}")
|
||||
}
|
||||
63 -> {
|
||||
if (data.size != 17 || data[16].toInt() !in 0..2) return invalid(type, data.size)
|
||||
require(data.size == 17) { "delivery needs 17 bytes" }
|
||||
val request = input.long
|
||||
if (_delivery.value?.request == request)
|
||||
_delivery.value = LocalDelivery(request, pending = false, received = data[16].toInt() == 1,
|
||||
forbidden = data[16].toInt() == 2)
|
||||
val peer = input.long
|
||||
val status = input.get().toInt() and 0xff
|
||||
require(request != 0L && peer != 0L && status in 0..2) { "invalid delivery request=$request peer=$peer status=$status" }
|
||||
val current = _delivery.value
|
||||
if (current?.request != request || !current.pending) {
|
||||
LogManager.addLog("DEBUG", "discovery", "stale delivery ignored request=$request peer=$peer status=$status"); return
|
||||
}
|
||||
if (current.device.nodeId != peer) {
|
||||
LogManager.addLog("WARN", "discovery", "delivery peer mismatch request=$request expected=${current.device.nodeId} got=$peer")
|
||||
return
|
||||
}
|
||||
_delivery.value = current.copy(pending = false, received = status == 1, forbidden = status == 2)
|
||||
LogManager.addLog(if (status == 1) "INFO" else "WARN", "discovery", "delivery completed request=$request peer=$peer status=$status")
|
||||
}
|
||||
64 -> {
|
||||
if (data.size != 1 || data[0].toInt() !in 0..1) return invalid(type, data.size)
|
||||
require(data.size == 1 && data[0].toInt() in 0..1) { "activity needs one byte 0/1" }
|
||||
setActive(data[0].toInt() == 1)
|
||||
}
|
||||
} } catch (error: Exception) {
|
||||
invalid(type, data.size, "${error.javaClass.simpleName}: ${error.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun invalid(type: Int, size: Int) { LogManager.addLog("WARN", "discovery", "invalid event type=$type bytes=$size") }
|
||||
private fun invalid(type: Int, size: Int, reason: String) {
|
||||
LogManager.addLog("WARN", "discovery", "invalid event type=$type bytes=$size: $reason")
|
||||
}
|
||||
|
||||
/** Считать непустую UTF-8 строку без замены испорченных байтов; имя поля попадает в диагностику, само значение — нет. */
|
||||
private fun readText(input: ByteBuffer, size: Int, field: String): String {
|
||||
require(size in 1..input.remaining()) { "truncated $field bytes=$size remaining=${input.remaining()}" }
|
||||
return try { ByteArray(size).also { input.get(it) }.decodeToString(throwOnInvalidSequence = true)
|
||||
} catch (error: CharacterCodingException) { throw IllegalArgumentException("invalid UTF-8 $field", error) }
|
||||
}
|
||||
|
||||
/** Формат chat_local.c: uint64 BE, длина и 1..127 байтов ника; ограничения совпадают с local_name_valid(). */
|
||||
private fun readDevice(input: ByteBuffer): LocalDevice {
|
||||
require(input.remaining() >= 9) { "truncated device header bytes=${input.remaining()}" }
|
||||
val id = input.long
|
||||
val size = input.get().toInt() and 0xff
|
||||
require(id != 0L && size in 1..127) { "invalid device id=$id name_bytes=$size" }
|
||||
val name = readText(input, size, "device name")
|
||||
require(name.none { it.code < 0x20 || it.code == 0x7f }) { "device name contains ASCII control characters" }
|
||||
return LocalDevice(id, name)
|
||||
}
|
||||
|
||||
private fun checkMain() {
|
||||
check(Looper.myLooper() === Looper.getMainLooper()) {
|
||||
val message = "LocalDiscovery requires main thread: caller=${Thread.currentThread().name}"
|
||||
LogManager.addLog("ERROR", "discovery", message); message
|
||||
}
|
||||
}
|
||||
|
||||
/** Сохраняет владельца до configure/acquire: Android-операция может бросить после побочного эффекта.
|
||||
* Не теряет lock при ошибке query/release; следующий ACTIVE/STOP повторит согласование состояния. */
|
||||
private fun setActive(active: Boolean) {
|
||||
var operation = "lookup"
|
||||
try {
|
||||
if (active && multicastLock?.isHeld != true) {
|
||||
val wifi = ChatApplication.instance.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
if (wifi == null) { LogManager.addLog("WARN", "discovery", "Wi-Fi service unavailable"); return }
|
||||
multicastLock = wifi.createMulticastLock("utun-local-discovery").apply { setReferenceCounted(false); acquire() }
|
||||
if (active) {
|
||||
var lock = multicastLock
|
||||
if (lock == null) {
|
||||
operation = "service"
|
||||
val wifi = ChatApplication.instance.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||
if (wifi == null) { LogManager.addLog("WARN", "discovery", "Wi-Fi service unavailable"); return }
|
||||
operation = "create"
|
||||
lock = wifi.createMulticastLock("utun-local-discovery")
|
||||
multicastLock = lock
|
||||
}
|
||||
operation = "query"
|
||||
if (lock.isHeld) return
|
||||
operation = "configure"; lock.setReferenceCounted(false)
|
||||
operation = "acquire"; lock.acquire()
|
||||
LogManager.addLog("INFO", "discovery", "Wi-Fi multicast receive enabled")
|
||||
} else if (!active) {
|
||||
multicastLock?.let { if (it.isHeld) it.release() }
|
||||
} else {
|
||||
val lock = multicastLock ?: return
|
||||
operation = "query"
|
||||
if (lock.isHeld) { operation = "release"; lock.release() }
|
||||
multicastLock = null
|
||||
LogManager.addLog("INFO", "discovery", "Wi-Fi multicast receive disabled")
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
LogManager.addLog("ERROR", "discovery", "multicast lock failed active=$active: ${error.message}")
|
||||
LogManager.addLog("ERROR", "discovery", "multicast lock failed active=$active operation=$operation retained=${multicastLock != null}: $error")
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -111,7 +111,9 @@ class LocalDiscoveryTest {
|
||||
assertNotEquals(0L, request); assertTrue(LocalDiscovery.delivery.value!!.pending)
|
||||
LocalDiscovery.onEvent(63, result(request, status = status))
|
||||
val value = LocalDiscovery.delivery.value!!
|
||||
assertEquals(device, value.device)
|
||||
assertFalse(value.pending); assertEquals(status == 1, value.received); assertEquals(status == 2, value.forbidden)
|
||||
if (status != 1) diagnostic("status=$status")
|
||||
LocalDiscovery.clearDelivery(); assertNull(LocalDiscovery.delivery.value)
|
||||
}
|
||||
}
|
||||
@@ -154,10 +156,11 @@ class LocalDiscoveryTest {
|
||||
NativeLib.sendLocal = { false }
|
||||
LocalDiscovery.send(device, link)
|
||||
assertFalse(LocalDiscovery.delivery.value!!.pending); diagnostic("enqueue")
|
||||
NativeLib.sendLocal = { throw IllegalStateException("native unavailable") }
|
||||
NativeLib.sendLocal = { throw IllegalStateException("native unavailable: $link") }
|
||||
val exception = runCatching { LocalDiscovery.send(device, link) }.exceptionOrNull()
|
||||
assertNull("send exception escaped: $exception", exception)
|
||||
assertFalse(LocalDiscovery.delivery.value!!.pending); diagnostic("send failed")
|
||||
assertTrue(LogManager.entries.none { link in it.message })
|
||||
}
|
||||
|
||||
@Test fun busySendIsReportedAndDoesNotReplacePendingRequest() {
|
||||
@@ -244,4 +247,14 @@ class LocalDiscoveryTest {
|
||||
assertTrue(context.wifiManager!!.locks.single().held)
|
||||
LocalDiscovery.onEvent(999, byteArrayOf(0)); diagnostic("999")
|
||||
}
|
||||
|
||||
@Test fun maximumDeviceCountNameAndInvitationSizesRemainAccepted() {
|
||||
val name = ("я".repeat(63) + "a").toByteArray()
|
||||
val rows = (1L..128L).map { row(it, name) }.toTypedArray()
|
||||
LocalDiscovery.onEvent(61, devices(*rows))
|
||||
assertEquals(128, LocalDiscovery.devices.value.size)
|
||||
val text = "utun://" + "a".repeat(1093)
|
||||
LocalDiscovery.onEvent(62, invite(name = name, text = text.toByteArray()))
|
||||
assertEquals(text, LocalDiscovery.invitations.value.single().link)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user