feat(receiver): 公布签名指纹与稳定 id,接入信令中继控制通道
- 新增 Fingerprint(签名证书 SHA-256)与 DeviceIdentity(持久化 deviceId)
- 信标 Offer、注册信息、配对码都带真实指纹,替换原先的空串/随机 UUID
- 新增 RelayClient(/relay 与 /relay/poll),ReceiverTransport 空闲时轮询握手
- 中继会话与直连互斥:握手期间不接管,进入中继后暂停直连重试
- 中继只承载控制帧,投屏请求直接回 DENIED;文件子协议改走统一的帧分发
- 文件分片支持 dataB64,异常统一回 {"op":"error"} 不再断链
This commit is contained in:
1 parent
2bf102c543
commit
22bac28914
8 files changed
+489
-55
No files matched your search
@@ -18,6 +18,7 @@ import android.widget.Toast
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.file.StorageAccess
|
||||
import com.ttstd.lancast.receiver.session.PairingCode
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import java.net.NetworkInterface
|
||||
|
||||
@@ -249,7 +250,7 @@ class MainActivity : Activity() {
|
||||
val pairingText = if (ip.isEmpty()) {
|
||||
"配对码:无法获取本机 IP"
|
||||
} else {
|
||||
"配对码:\n${PairingCode.build(ip, 41001, "")}"
|
||||
"配对码:\n${PairingCode.build(ip, 41001, Fingerprint.of(this))}"
|
||||
}
|
||||
runOnUiThread {
|
||||
endpoint.text = endpointText
|
||||
|
||||
+4
-2
@@ -21,8 +21,9 @@ import android.widget.Toast
|
||||
import com.ttstd.lancast.receiver.discovery.HostBeacon
|
||||
import com.ttstd.lancast.receiver.file.FileHttpServer
|
||||
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import com.ttstd.lancast.receiver.util.Privileged
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* 常驻前台服务。分两个阶段:
|
||||
@@ -274,10 +275,11 @@ class MediaProjectionService : Service() {
|
||||
val metrics = realMetrics()
|
||||
beacon = HostBeacon(
|
||||
HostBeacon.Offer(
|
||||
id = UUID.randomUUID().toString(),
|
||||
id = DeviceIdentity.of(this),
|
||||
name = "Android Receiver",
|
||||
model = Build.MODEL ?: "Android",
|
||||
resolution = "${metrics.widthPixels}x${metrics.heightPixels}",
|
||||
fingerprint = Fingerprint.of(this),
|
||||
),
|
||||
).also { it.start() }
|
||||
}
|
||||
|
||||
@@ -24,9 +24,10 @@ import com.ttstd.lancast.receiver.file.FileService
|
||||
import com.ttstd.lancast.receiver.input.InputInjector
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.session.ReceiverTransport
|
||||
import com.ttstd.lancast.receiver.util.DeviceIdentity
|
||||
import com.ttstd.lancast.receiver.util.Fingerprint
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
@@ -63,7 +64,10 @@ class ReceiverSession(
|
||||
private val opusEncoder = OpusEncoder()
|
||||
private val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val fingerprint: String = ""
|
||||
/** 本机身份指纹(应用签名证书 SHA-256),用于主控端 TOFU pinning。 */
|
||||
private val fingerprint: String = Fingerprint.of(context)
|
||||
/** 稳定的设备 id(首次运行生成后持久化),保证 pinning 能对上同一台设备。 */
|
||||
private val deviceId: String = DeviceIdentity.of(context)
|
||||
|
||||
@Volatile
|
||||
private var transport: ReceiverTransport? = null
|
||||
@@ -259,7 +263,7 @@ class ReceiverSession(
|
||||
private fun startPublishing() {
|
||||
val size = currentScreenSize()
|
||||
val device = AnnouncedDevice(
|
||||
id = UUID.randomUUID().toString(),
|
||||
id = deviceId,
|
||||
name = "Android Receiver",
|
||||
ip = localIp,
|
||||
mediaPort = 41000,
|
||||
@@ -303,6 +307,8 @@ class ReceiverSession(
|
||||
injector,
|
||||
clipboard,
|
||||
fileService,
|
||||
signalingUrl,
|
||||
deviceId,
|
||||
)
|
||||
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
|
||||
created.onSessionConfig = { json -> applySessionConfig(json) }
|
||||
|
||||
+3
-1
@@ -33,6 +33,8 @@ class HostBeacon(
|
||||
val name: String,
|
||||
val model: String,
|
||||
val resolution: String,
|
||||
/** 应用签名证书指纹,主控端据此做 TOFU pinning。 */
|
||||
val fingerprint: String = "",
|
||||
)
|
||||
|
||||
companion object {
|
||||
@@ -159,7 +161,7 @@ class HostBeacon(
|
||||
put("ctrl", controlPort)
|
||||
put("media", mediaPort)
|
||||
put("audio", audioPort)
|
||||
put("fp", "")
|
||||
put("fp", device.fingerprint)
|
||||
put(
|
||||
"cap",
|
||||
JSONArray(
|
||||
|
||||
+306
-48
@@ -1,12 +1,14 @@
|
||||
package com.ttstd.lancast.receiver.session
|
||||
|
||||
import android.media.MediaCodec
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
|
||||
import com.ttstd.lancast.receiver.file.FileService
|
||||
import com.ttstd.lancast.receiver.input.InputInjector
|
||||
import com.ttstd.lancast.receiver.protocol.ControlEvent
|
||||
import com.ttstd.lancast.receiver.protocol.ControlFrames
|
||||
import com.ttstd.lancast.receiver.protocol.MirrorAction
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
@@ -20,10 +22,13 @@ import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* demo v1 传输层:
|
||||
* 1. TCP 反连 host:controlPort,先做 ECDH P-256 握手(互发 65 字节公钥)。
|
||||
* 1. 优先 TCP 反连 host:controlPort,先做 ECDH P-256 握手(互发 65 字节公钥)。
|
||||
* 2. 派生 control/video/audio 三把会话密钥。
|
||||
* 3. 控制帧使用 AES-256-GCM(8 字节明头作 AAD);媒体包使用 HMAC-SHA256 截断 MAC。
|
||||
*
|
||||
* 跨网段时(TCP 直连不通)可用信令服务器中继控制通道:协议与直连完全一致,
|
||||
* 只是把加密帧整帧塞进 `/relay` 消息。中继不承载视频/音频,投屏请求会被直接拒绝。
|
||||
*
|
||||
* 握手后控制通道的机密性由控制帧 AES-GCM 保证,demo 阶段不再叠加 TLS。
|
||||
*/
|
||||
class ReceiverTransport(
|
||||
@@ -36,6 +41,8 @@ class ReceiverTransport(
|
||||
private val injector: InputInjector,
|
||||
private val clipboard: ClipboardBridge,
|
||||
private val fileService: FileService,
|
||||
private val signalingUrl: String = "",
|
||||
private val deviceId: String = "",
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ReceiverTransport"
|
||||
@@ -45,14 +52,23 @@ class ReceiverTransport(
|
||||
|
||||
/** 连续失败时的最大退避间隔。 */
|
||||
private const val MAX_RETRY_MS = 5000L
|
||||
|
||||
/** 中继空闲轮询间隔:没有会话时慢一点,避免空转打信令服务器。 */
|
||||
private const val RELAY_IDLE_POLL_MS = 400L
|
||||
|
||||
/** 中继会话内的轮询间隔。 */
|
||||
private const val RELAY_POLL_MS = 120L
|
||||
}
|
||||
|
||||
/** 握手阶段失败:对端未就绪/已断开,属于可预期情况。 */
|
||||
private class HandshakeException(message: String, cause: Throwable) :
|
||||
Exception(message, cause)
|
||||
|
||||
private val executor = Executors.newFixedThreadPool(2)
|
||||
private val crypto = SessionCrypto()
|
||||
private val executor = Executors.newFixedThreadPool(3)
|
||||
|
||||
/** 中继会话会换一套临时密钥,所以不能是 val。 */
|
||||
@Volatile
|
||||
private var crypto = SessionCrypto()
|
||||
|
||||
/** 连续失败次数,仅用于日志去抖(只在连接线程内读写)。 */
|
||||
private var consecutiveFailures = 0
|
||||
@@ -60,6 +76,21 @@ class ReceiverTransport(
|
||||
private var output: DataOutputStream? = null
|
||||
private var udp: DatagramSocket? = null
|
||||
private var keys: SessionCrypto.SessionKeys? = null
|
||||
|
||||
/** 当前是否由中继会话占用控制通道(此时不再尝试直连)。 */
|
||||
@Volatile
|
||||
private var relayMode = false
|
||||
|
||||
/** 直连正在做 ECDH 握手:中继会话要等它结束,避免两套密钥互相覆盖。 */
|
||||
@Volatile
|
||||
private var handshaking = false
|
||||
|
||||
/** 中继会话的对端 id,非空时 [writeFrame] 走信令服务器。 */
|
||||
@Volatile
|
||||
private var relayPeerId: String? = null
|
||||
@Volatile
|
||||
private var relayClient: RelayClient? = null
|
||||
|
||||
@Volatile
|
||||
private var active = false
|
||||
@Volatile
|
||||
@@ -92,9 +123,17 @@ class ReceiverTransport(
|
||||
fun start() {
|
||||
if (active) return
|
||||
active = true
|
||||
// 配了信令服务器就同时监听中继请求(主控端跨网段时会用这种方式拨过来)。
|
||||
if (signalingUrl.isNotBlank() && deviceId.isNotBlank()) {
|
||||
executor.execute { relayListenerLoop() }
|
||||
}
|
||||
executor.execute {
|
||||
var retryDelayMs = INITIAL_RETRY_MS
|
||||
while (active) {
|
||||
if (relayMode) {
|
||||
sleepQuietly(300)
|
||||
continue
|
||||
}
|
||||
var handshakeDone = false
|
||||
try {
|
||||
handshakeDone = connectAndRun()
|
||||
@@ -134,14 +173,21 @@ class ReceiverTransport(
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
// 对端在这期间关闭连接(主控端未开监听、正在重启、或只接受一路连接)都属于
|
||||
// 可预期情况,单独包一层异常,日志里给出人能看懂的原因。
|
||||
val localCrypto = crypto
|
||||
handshaking = true
|
||||
try {
|
||||
output?.write(crypto.publicBytes)
|
||||
output?.write(localCrypto.publicBytes)
|
||||
output?.flush()
|
||||
val peerPublic = ByteArray(65)
|
||||
input.readFully(peerPublic)
|
||||
keys = crypto.deriveKeys(peerPublic)
|
||||
if (relayMode) {
|
||||
throw HandshakeException("直连握手期间已切换到中继", java.io.IOException("relay"))
|
||||
}
|
||||
keys = localCrypto.deriveKeys(peerPublic)
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException(describeHandshakeFailure(error), error)
|
||||
} finally {
|
||||
handshaking = false
|
||||
}
|
||||
|
||||
udp = DatagramSocket()
|
||||
@@ -193,7 +239,6 @@ class ReceiverTransport(
|
||||
}
|
||||
|
||||
private fun resetConnection() {
|
||||
running = false
|
||||
try {
|
||||
socket?.close()
|
||||
udp?.close()
|
||||
@@ -202,6 +247,11 @@ class ReceiverTransport(
|
||||
socket = null
|
||||
output = null
|
||||
udp = null
|
||||
if (relayMode) {
|
||||
// 中继会话自行管理 keys/running,直连的收尾不能把它们清掉。
|
||||
return
|
||||
}
|
||||
running = false
|
||||
keys = null
|
||||
}
|
||||
|
||||
@@ -271,6 +321,8 @@ class ReceiverTransport(
|
||||
|
||||
fun close() {
|
||||
active = false
|
||||
// 先退出中继模式,让 resetConnection 走正常清理路径。
|
||||
relayMode = false
|
||||
resetConnection()
|
||||
}
|
||||
|
||||
@@ -289,24 +341,7 @@ class ReceiverTransport(
|
||||
if (length < 0 || length > 16 * 1024 * 1024) break
|
||||
val rest = ByteArray(12 + length + 16)
|
||||
input.readFully(rest)
|
||||
val secureFrame = header + rest
|
||||
val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: continue
|
||||
when (plaintext[1].toInt() and 0xff) {
|
||||
7 -> handleFileFrame(plaintext.copyOfRange(8, plaintext.size))
|
||||
else -> {
|
||||
val frame = ControlFrames.decode(plaintext) ?: continue
|
||||
when (val event = frame.event) {
|
||||
is ControlEvent.Clipboard -> if (clipboardSyncEnabled) {
|
||||
clipboard.publish(event.text)
|
||||
}
|
||||
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
|
||||
is ControlEvent.Pong -> Unit
|
||||
is ControlEvent.Mirror -> onMirrorEvent?.invoke(event.action, event.message)
|
||||
is ControlEvent.SessionConfig -> onSessionConfig?.invoke(event.json)
|
||||
else -> injector.inject(frame)
|
||||
}
|
||||
}
|
||||
}
|
||||
dispatchSecureFrame(header + rest, controlKey)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
// 主控端关闭是正常断线,属于可恢复状态,交给外层重连。
|
||||
@@ -314,35 +349,248 @@ class ReceiverTransport(
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleFileFrame(payload: ByteArray) {
|
||||
val request = JSONObject(String(payload, StandardCharsets.UTF_8))
|
||||
when (request.optString("op")) {
|
||||
"prepare" -> sendRaw(7, fileService.prepare(request.getString("body")))
|
||||
"chunk" -> {
|
||||
val received = fileService.writeChunk(
|
||||
request.getString("sessionId"),
|
||||
request.getString("fileId"),
|
||||
request.getString("token"),
|
||||
request.getLong("offset"),
|
||||
request.getString("data").toByteArray(StandardCharsets.ISO_8859_1),
|
||||
)
|
||||
sendRaw(7, JSONObject().put("op", "chunkAck").put("received", received).toString())
|
||||
}
|
||||
"progress" -> sendRaw(7, fileService.progress(request.getString("sessionId")))
|
||||
"cancel" -> fileService.cancel(request.getString("sessionId"))
|
||||
"list" -> {
|
||||
val json = try {
|
||||
JSONObject(fileService.list(request.optString("path", ""))).put("op", "list")
|
||||
} catch (error: Exception) {
|
||||
JSONObject()
|
||||
.put("op", "list")
|
||||
.put("error", error.message ?: "目录浏览失败")
|
||||
/** 解密并分发一帧控制数据;直连与中继共用同一套处理逻辑。 */
|
||||
private fun dispatchSecureFrame(secureFrame: ByteArray, controlKey: ByteArray) {
|
||||
val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: return
|
||||
if (plaintext.size < 8) return
|
||||
when (plaintext[1].toInt() and 0xff) {
|
||||
7 -> handleFileFrame(plaintext.copyOfRange(8, plaintext.size))
|
||||
else -> {
|
||||
val frame = ControlFrames.decode(plaintext) ?: return
|
||||
when (val event = frame.event) {
|
||||
is ControlEvent.Clipboard -> if (clipboardSyncEnabled) {
|
||||
clipboard.publish(event.text)
|
||||
}
|
||||
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
|
||||
is ControlEvent.Pong -> Unit
|
||||
is ControlEvent.Mirror -> {
|
||||
if (relayMode && event.action == MirrorAction.REQUEST) {
|
||||
// 中继只走控制帧,视频/音频仍需 UDP 直连,先明确拒绝并说明原因。
|
||||
sendMirror(MirrorAction.DENIED, "中继模式不支持投屏,请在同一网段直连后再试")
|
||||
} else {
|
||||
onMirrorEvent?.invoke(event.action, event.message)
|
||||
}
|
||||
}
|
||||
is ControlEvent.SessionConfig -> onSessionConfig?.invoke(event.json)
|
||||
else -> injector.inject(frame)
|
||||
}
|
||||
sendRaw(7, json.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 空闲时轮询信令服务器,等待主控端发来的 `hs`。
|
||||
*
|
||||
* 中继与直连互斥:一旦进入中继会话,[relayMode] 会置位,直连重试暂停;
|
||||
* 会话结束(对端 `bye` 或网络中断)后再重新尝试直连。
|
||||
*/
|
||||
private fun relayListenerLoop() {
|
||||
val client = RelayClient(signalingUrl)
|
||||
while (active) {
|
||||
if (relayMode || keys != null || handshaking) {
|
||||
sleepQuietly(300)
|
||||
continue
|
||||
}
|
||||
val messages = try {
|
||||
client.poll(deviceId)
|
||||
} catch (_: Exception) {
|
||||
// 信令不可达是常态(本地直连场景),安静重试。
|
||||
sleepQuietly(1500)
|
||||
continue
|
||||
}
|
||||
var hello: JSONObject? = null
|
||||
for (message in messages) {
|
||||
if (
|
||||
message.optString("ttstd") == RelayClient.PROTOCOL &&
|
||||
message.optString("kind") == "hs"
|
||||
) {
|
||||
hello = message
|
||||
break
|
||||
}
|
||||
}
|
||||
if (hello == null) {
|
||||
sleepQuietly(RELAY_IDLE_POLL_MS)
|
||||
continue
|
||||
}
|
||||
relaySession(client, hello)
|
||||
}
|
||||
}
|
||||
|
||||
/** 完成一次中继握手并进入控制帧收发循环,返回即表示会话结束。 */
|
||||
private fun relaySession(client: RelayClient, hello: JSONObject) {
|
||||
val peerId = hello.optString("from")
|
||||
if (peerId.isEmpty()) return
|
||||
val peerPublic = try {
|
||||
Base64.decode(hello.optString("pub"), Base64.DEFAULT)
|
||||
} catch (_: Exception) {
|
||||
return
|
||||
}
|
||||
if (peerPublic.size != 65) {
|
||||
Log.w(TAG, "中继握手公钥长度非法: ${peerPublic.size}")
|
||||
return
|
||||
}
|
||||
val sessionCrypto = SessionCrypto()
|
||||
val sessionKeys = try {
|
||||
sessionCrypto.deriveKeys(peerPublic)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "中继握手失败: ${error.message}")
|
||||
return
|
||||
}
|
||||
val ack = JSONObject()
|
||||
.put("ttstd", RelayClient.PROTOCOL)
|
||||
.put("kind", "hsAck")
|
||||
.put("from", deviceId)
|
||||
.put("pub", Base64.encodeToString(sessionCrypto.publicBytes, Base64.NO_WRAP))
|
||||
try {
|
||||
client.send(deviceId, peerId, ack)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "中继握手应答发送失败: ${error.message}")
|
||||
return
|
||||
}
|
||||
|
||||
relayMode = true
|
||||
relayPeerId = peerId
|
||||
relayClient = client
|
||||
crypto = sessionCrypto
|
||||
keys = sessionKeys
|
||||
running = true
|
||||
consecutiveFailures = 0
|
||||
Log.i(TAG, "已通过中继连接 $peerId")
|
||||
try {
|
||||
relayReadLoop(client, sessionKeys.control, peerId)
|
||||
} catch (error: Exception) {
|
||||
Log.i(TAG, "中继会话断开: ${error.javaClass.simpleName} ${error.message ?: ""}".trim())
|
||||
} finally {
|
||||
client.sendBye(deviceId, peerId)
|
||||
running = false
|
||||
keys = null
|
||||
relayMode = false
|
||||
relayPeerId = null
|
||||
relayClient = null
|
||||
crypto = SessionCrypto()
|
||||
Log.i(TAG, "中继会话结束: $peerId")
|
||||
}
|
||||
}
|
||||
|
||||
private fun relayReadLoop(
|
||||
client: RelayClient,
|
||||
controlKey: ByteArray,
|
||||
peerId: String,
|
||||
) {
|
||||
var pingSequence = 0
|
||||
var lastPing = System.currentTimeMillis()
|
||||
var consecutiveErrors = 0
|
||||
while (running && active) {
|
||||
val messages = try {
|
||||
client.poll(deviceId)
|
||||
} catch (_: Exception) {
|
||||
consecutiveErrors++
|
||||
// 断网/信令重启:连续 20 次(约 12 秒)放弃本次会话,交给上层重连。
|
||||
if (consecutiveErrors >= 20) return
|
||||
sleepQuietly(600)
|
||||
continue
|
||||
}
|
||||
consecutiveErrors = 0
|
||||
for (message in messages) {
|
||||
if (message.optString("ttstd") != RelayClient.PROTOCOL) continue
|
||||
// 只接受本会话对端的内容,其它设备串进来的消息一律忽略。
|
||||
if (message.optString("from") != peerId) continue
|
||||
when (message.optString("kind")) {
|
||||
"frame" -> {
|
||||
val data = try {
|
||||
Base64.decode(message.optString("data"), Base64.DEFAULT)
|
||||
} catch (_: Exception) {
|
||||
continue
|
||||
}
|
||||
dispatchSecureFrame(data, controlKey)
|
||||
}
|
||||
"bye" -> return
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastPing >= 2000) {
|
||||
pingSequence++
|
||||
sendControl(ControlEvent.Ping(pingSequence.toLong()))
|
||||
lastPing = now
|
||||
}
|
||||
sleepQuietly(RELAY_POLL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sleepQuietly(millis: Long) {
|
||||
try {
|
||||
Thread.sleep(millis)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleFileFrame(payload: ByteArray) {
|
||||
val request = JSONObject(String(payload, StandardCharsets.UTF_8))
|
||||
// 文件子协议是主控端发起的一问一答;任何一条失败都要回错误响应,
|
||||
// 不能把异常抛到 readLoop(会直接断开整条控制通道)。
|
||||
try {
|
||||
when (request.optString("op")) {
|
||||
"prepare" -> sendRaw(
|
||||
7,
|
||||
JSONObject(fileService.prepare(request.getString("body")))
|
||||
.put("op", "prepare")
|
||||
.toString(),
|
||||
)
|
||||
"chunk" -> {
|
||||
val received = fileService.writeChunk(
|
||||
request.getString("sessionId"),
|
||||
request.getString("fileId"),
|
||||
request.getString("token"),
|
||||
request.getLong("offset"),
|
||||
chunkBytes(request),
|
||||
)
|
||||
sendRaw(7, JSONObject().put("op", "chunkAck").put("received", received).toString())
|
||||
}
|
||||
"progress" -> sendRaw(
|
||||
7,
|
||||
JSONObject(fileService.progress(request.getString("sessionId")))
|
||||
.put("op", "progress")
|
||||
.toString(),
|
||||
)
|
||||
"cancel" -> fileService.cancel(request.getString("sessionId"))
|
||||
"list" -> sendRaw(
|
||||
7,
|
||||
JSONObject(fileService.list(request.optString("path", "")))
|
||||
.put("op", "list")
|
||||
.toString(),
|
||||
)
|
||||
else -> sendRaw(
|
||||
7,
|
||||
JSONObject()
|
||||
.put("op", "error")
|
||||
.put("error", "未知文件操作: ${request.optString("op")}")
|
||||
.toString(),
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "文件子协议处理失败: ${error.message}")
|
||||
sendRaw(
|
||||
7,
|
||||
JSONObject()
|
||||
.put("op", "error")
|
||||
.put("error", error.message ?: "文件子协议处理失败")
|
||||
.toString(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分片内容:优先 `dataB64`(标准 base64,二进制安全),
|
||||
* 兼容老客户端的 `data`(按 ISO-8859-1 逐字节还原)。
|
||||
*/
|
||||
private fun chunkBytes(request: JSONObject): ByteArray {
|
||||
val base64 = request.optString("dataB64")
|
||||
if (base64.isNotEmpty()) return Base64.decode(base64, Base64.DEFAULT)
|
||||
return request.getString("data").toByteArray(StandardCharsets.ISO_8859_1)
|
||||
}
|
||||
|
||||
private fun sendRaw(msgType: Int, text: String) {
|
||||
val controlKey = keys?.control ?: return
|
||||
val payload = text.toByteArray(StandardCharsets.UTF_8)
|
||||
@@ -353,6 +601,16 @@ class ReceiverTransport(
|
||||
|
||||
@Synchronized
|
||||
private fun writeFrame(frame: ByteArray) {
|
||||
val client = relayClient
|
||||
val peerId = relayPeerId
|
||||
if (client != null && peerId != null) {
|
||||
// 中继把整帧放进一条消息;发送失败由读循环感知并结束会话。
|
||||
try {
|
||||
client.sendFrame(deviceId, peerId, frame)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
output?.write(frame)
|
||||
output?.flush()
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ttstd.lancast.receiver.session
|
||||
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* 信令服务器 `/relay` 的最小客户端:只负责入队/出队,不解析业务内容。
|
||||
*
|
||||
* 协议见 `rust_core/src/session/relay.rs`:
|
||||
* `hs` / `hsAck` 交换 ECDH 公钥,之后每次携带一条完整的加密控制帧(`frame`)。
|
||||
* 服务器不保留会话状态,消息 5 分钟后过期,因此双方都要靠轮询与心跳维持。
|
||||
*/
|
||||
class RelayClient(
|
||||
baseUrl: String,
|
||||
private val timeoutMs: Int = 3000,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "RelayClient"
|
||||
|
||||
/** 中继信封版本,与 Rust 侧 `RELAY_PROTOCOL` 保持一致。 */
|
||||
const val PROTOCOL = "relay/1"
|
||||
}
|
||||
|
||||
private val base = baseUrl.trim().trimEnd('/')
|
||||
|
||||
fun poll(deviceId: String): List<JSONObject> {
|
||||
val response = request("GET", "/relay/poll?deviceId=${encode(deviceId)}", null)
|
||||
val messages = JSONObject(response).optJSONArray("messages") ?: return emptyList()
|
||||
val result = ArrayList<JSONObject>(messages.length())
|
||||
for (index in 0 until messages.length()) {
|
||||
messages.optJSONObject(index)?.let(result::add)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun send(from: String, to: String, payload: JSONObject) {
|
||||
val body = JSONObject()
|
||||
.put("from", from)
|
||||
.put("to", to)
|
||||
.put("payload", payload)
|
||||
request("POST", "/relay", body.toString())
|
||||
}
|
||||
|
||||
/** 发送一帧已加密的控制帧(整帧放进一条中继消息,避免再做流式重组)。 */
|
||||
fun sendFrame(from: String, to: String, frame: ByteArray) {
|
||||
val payload = JSONObject()
|
||||
.put("ttstd", PROTOCOL)
|
||||
.put("kind", "frame")
|
||||
.put("from", from)
|
||||
.put("data", Base64.encodeToString(frame, Base64.NO_WRAP))
|
||||
send(from, to, payload)
|
||||
}
|
||||
|
||||
fun sendBye(from: String, to: String) {
|
||||
val payload = JSONObject()
|
||||
.put("ttstd", PROTOCOL)
|
||||
.put("kind", "bye")
|
||||
.put("from", from)
|
||||
runCatching { send(from, to, payload) }
|
||||
}
|
||||
|
||||
private fun request(method: String, path: String, body: String?): String {
|
||||
val connection = URL(base + path).openConnection() as HttpURLConnection
|
||||
return try {
|
||||
connection.requestMethod = method
|
||||
connection.connectTimeout = timeoutMs
|
||||
connection.readTimeout = timeoutMs
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
if (body != null) {
|
||||
connection.doOutput = true
|
||||
connection.outputStream.use { it.write(body.toByteArray(StandardCharsets.UTF_8)) }
|
||||
}
|
||||
val code = connection.responseCode
|
||||
val stream = if (code in 200..299) connection.inputStream else connection.errorStream
|
||||
val text = stream?.bufferedReader(StandardCharsets.UTF_8)?.use { it.readText() } ?: ""
|
||||
if (code !in 200..299) {
|
||||
throw IllegalStateException("信令 HTTP $code: ${text.trim()}")
|
||||
}
|
||||
text
|
||||
} catch (error: Exception) {
|
||||
Log.d(TAG, "中继请求失败 $method $path: ${error.message}")
|
||||
throw error
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.ttstd.lancast.receiver.util
|
||||
|
||||
import android.content.Context
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* 稳定的本机设备 id。
|
||||
*
|
||||
* 之前每次启动都随机 UUID,导致主控端无法把「指纹」和「设备」对应起来(每次都是新设备),
|
||||
* 换个 id 就能绕过 pinning。这里把 id 落到 SharedPreferences,只在首次运行生成。
|
||||
*/
|
||||
object DeviceIdentity {
|
||||
private const val PREFS = "ttstd_identity"
|
||||
private const val KEY_ID = "deviceId"
|
||||
|
||||
fun of(context: Context): String {
|
||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
prefs.getString(KEY_ID, null)?.takeIf { it.isNotBlank() }?.let { return it }
|
||||
val created = UUID.randomUUID().toString()
|
||||
prefs.edit().putString(KEY_ID, created).apply()
|
||||
return created
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ttstd.lancast.receiver.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* 本机身份指纹:应用签名证书的 SHA-256。
|
||||
*
|
||||
* 用途是让主控端能把「这台设备」钉住(TOFU pinning):
|
||||
* - 同一份签名安装出来的应用指纹恒定,重装/升级不变;
|
||||
* - 换了签名(例如换成正式签名包)指纹就变,主控端会提示重新确认。
|
||||
*
|
||||
* 注意它绑定的是应用身份,不是本次 ECDH 的临时公钥,因此只能发现「对端换了个应用」,
|
||||
* 不能替代对密钥交换本身的认证(详见 README §4.3)。
|
||||
*/
|
||||
object Fingerprint {
|
||||
private const val TAG = "Fingerprint"
|
||||
|
||||
fun of(context: Context): String {
|
||||
val signature = try {
|
||||
val info = context.packageManager.getPackageInfo(
|
||||
context.packageName,
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
PackageManager.GET_SIGNING_CERTIFICATES
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
PackageManager.GET_SIGNATURES
|
||||
},
|
||||
)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
info.signingInfo?.apkContentsSigners?.firstOrNull()
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
info.signatures?.firstOrNull()
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "读取应用签名失败: ${error.message}")
|
||||
null
|
||||
}
|
||||
if (signature == null) return ""
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(signature.toByteArray())
|
||||
val hex = digest.joinToString("") { byte -> "%02x".format(byte) }
|
||||
return "sha256:$hex"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user