feat(security): 完善信令认证与媒体加密

- 增加信令访问令牌、HTTPS 校验、限流及跨网段中继连接修复
- 同步三端媒体 v2 协议,实现 AES-GCM、防重放和乱序分片重组,升级 Rust ABI 6
- 修复文件鉴权、权限协商及剪贴板越权,完善上传校验和串流超时处理
- 增加跨端回归测试及部署文档,在 AGENTS.md 记录真机与真实跨网段待验收项目
This commit is contained in:
tongtong committed 2026-11-28 06:37:24 +08:00
1 parent 4c9d006d11
commit f6b7730684
58 files changed
+2167 -218

No files matched your search

@@ -0,0 +1,76 @@
package com.ttstd.lancast.receiver
import android.app.Activity
import android.app.Instrumentation
import android.os.Bundle
import com.ttstd.lancast.receiver.session.MediaPackets
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/** Real Android JCA provider interoperability test; no extra test dependencies. */
class MediaProtocolInstrumentation : Instrumentation() {
private var args = Bundle()
override fun onCreate(arguments: Bundle?) { super.onCreate(arguments); args = arguments ?: Bundle(); start() }
override fun onStart() {
val result = Bundle()
try {
val key = ByteArray(32) { it.toByte() }
val payload = "android-media-v2".toByteArray()
val packet = MediaPackets.encode(payload, 42, 1, key)
check(packet.size == payload.size + MediaPackets.OVERHEAD)
check(decrypt(packet, key).contentEquals(payload))
check(!MediaPackets.encode(payload, 42, 1, key).contentEquals(packet))
val tampered = packet.clone().apply { this[lastIndex] = (this[lastIndex].toInt() xor 1).toByte() }
check(runCatching { decrypt(tampered,key) }.isFailure)
check(runCatching { decrypt(packet,ByteArray(32)) }.isFailure)
check(runCatching { MediaPackets.encode(ByteArray(1153),42,1,key) }.isFailure)
val audio = MediaPackets.encode(byteArrayOf(0,1,2,3),42,0x82,key)
check(decrypt(audio,key).contentEquals(byteArrayOf(0,1,2,3)))
val rust = args.getString("rustPacket")
if (!rust.isNullOrEmpty()) check(decrypt(unhex(rust),key).contentEquals("rust-media-v2".toByteArray()))
result.putString("androidPacket", packet.joinToString("") { "%02x".format(it) })
args.getString("targetHost")?.let { host ->
val frame = MediaPackets.nextFrameId()
val parts = listOf("android-", "wsl-", "media").mapIndexed { index, value ->
MediaPackets.encode(value.toByteArray(),42,1,key,frame,index,3)
}
val damaged = parts[1].clone().apply { this[lastIndex] = (this[lastIndex].toInt() xor 1).toByte() }
DatagramSocket().use { socket ->
val address = InetAddress.getByName(host)
for (bytes in listOf(parts[2],parts[0],parts[0],damaged,parts[1],parts[2],ByteArray(40))) {
socket.send(DatagramPacket(bytes,bytes.size,address,args.getString("targetPort","42004").toInt()))
Thread.sleep(30)
}
}
}
result.putString("result", "PASS: Android AES-GCM, tamper, key, nonce and Rust interoperability")
finish(Activity.RESULT_OK,result)
} catch (error: Throwable) {
result.putString("error",error.stackTraceToString())
finish(Activity.RESULT_CANCELED,result)
}
}
private fun unhex(value:String):ByteArray = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun decrypt(packet:ByteArray,key:ByteArray):ByteArray {
check(packet.copyOfRange(0,4).contentEquals("TTM2".toByteArray()))
val header = packet.copyOfRange(0,37)
check(ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN).getInt(33) == packet.size-65)
val prk = hmac("ttstdconnect-v1".toByteArray(),key)
val derived = hmac(prk,"lancast/media/packet/v2".toByteArray()+byteArrayOf(1))
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE,SecretKeySpec(derived,"AES"),GCMParameterSpec(128,packet.copyOfRange(37,49)))
updateAAD(header)
}
return cipher.doFinal(packet.copyOfRange(49,packet.size))
}
private fun hmac(key:ByteArray,bytes:ByteArray):ByteArray = Mac.getInstance("HmacSHA256").apply {
init(SecretKeySpec(key,"HmacSHA256"))
}.doFinal(bytes)
}
@@ -11,6 +11,8 @@ import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.text.InputType
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RadioButton
@@ -156,6 +158,31 @@ class MainActivity : Activity() {
}
}
val signalUrl = EditText(this).apply {
hint = "外部信令地址(https://signal.example.com)"
setSingleLine(true)
setText(Prefs.signalingUrl(this@MainActivity))
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
}
val signalToken = EditText(this).apply {
hint = "信令访问令牌"
setSingleLine(true)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
setText(Prefs.signalingToken(this@MainActivity))
}
val saveSignaling = Button(this).apply {
text = "保存跨网段设置"
setOnClickListener {
val url = signalUrl.text.toString().trim()
val uri = android.net.Uri.parse(url)
if (url.isNotEmpty() && (uri.scheme !in listOf("http", "https") || uri.host.isNullOrBlank() || uri.fragment != null || uri.userInfo != null)) {
Toast.makeText(this@MainActivity, "信令地址格式无效", Toast.LENGTH_SHORT).show()
} else {
Prefs.setSignaling(this@MainActivity, url, signalToken.text.toString().trim())
Toast.makeText(this@MainActivity, "已保存,请停止后重新启动待命服务", Toast.LENGTH_LONG).show()
}
}
}
val content = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(48, 64, 48, 64)
@@ -169,6 +196,9 @@ class MainActivity : Activity() {
addView(accessGroup)
addView(authorize)
addView(startButton)
addView(signalUrl)
addView(signalToken)
addView(saveSignaling)
addView(storageInfo)
addView(storageButton)
addView(fileInfo)
@@ -202,7 +232,7 @@ class MainActivity : Activity() {
// ------------------------------------------------------------------ 动作
private fun startStandby() {
MediaProjectionService.start(this, hostOverride, "")
MediaProjectionService.start(this, hostOverride)
status.text = "状态:正在进入待命…"
handler.postDelayed({ refreshStatus }, 300)
}
@@ -132,7 +132,7 @@ class MediaProjectionService : Service() {
get() = com.ttstd.lancast.receiver.discovery.HostBeacon.lastHost
/** 启动待命服务(不需要屏幕录制授权)。 */
fun start(context: Context, host: String = "", signalingUrl: String = "") {
fun start(context: Context, host: String = "", signalingUrl: String = Prefs.signalingEndpoint(context)) {
val intent = Intent(context, MediaProjectionService::class.java).apply {
action = ACTION_START
putExtra(EXTRA_HOST, host)
@@ -13,6 +13,18 @@ import java.security.SecureRandom
* - [fileToken]:文件服务访问令牌,首次使用时生成,显示在主界面供主控端填写。
*/
object Prefs {
fun signalingUrl(context: Context): String = prefs(context).getString("signaling_url", "").orEmpty()
fun signalingToken(context: Context): String = prefs(context).getString("signaling_token", "").orEmpty()
fun setSignaling(context: Context, url: String, token: String) {
prefs(context).edit().putString("signaling_url", url).putString("signaling_token", token).apply()
}
fun signalingEndpoint(context: Context): String {
val base = signalingUrl(context)
if (base.isBlank()) return ""
val token = signalingToken(context)
return android.net.Uri.parse(base).buildUpon()
.encodedFragment(if (token.isEmpty()) null else "token=" + android.net.Uri.encode(token)).build().toString()
}
private const val NAME = "lancast_receiver_prefs"
private const val KEY_AUTO_GRANT = "auto_grant"
private const val KEY_FILE_SERVICE = "file_service_enabled"
@@ -26,6 +26,7 @@ import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.AccessLevel
import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.session.ReceiverTransport
import com.ttstd.lancast.receiver.session.MediaPackets
import com.ttstd.lancast.receiver.util.DeviceIdentity
import com.ttstd.lancast.receiver.util.Fingerprint
import com.ttstd.lancast.receiver.util.TlsIdentity
@@ -169,7 +170,7 @@ class ReceiverSession(
* @return 是否成功建立采集链路。
*/
fun beginMirroring(projection: MediaProjection?): Boolean {
if (!running) return false
if (!running || transport?.mediaProtocolReady != true) return false
synchronized(captureLock) {
if (mirroring) return true
this.projection = projection
@@ -299,7 +300,7 @@ class ReceiverSession(
controlPort = 41001,
fingerprint = this@ReceiverSession.fingerprint,
capabilities = listOf(
"h264", "opus", "uibc", "clipboard", "file", "mirror-request", "file-browse",
"h264", "pcm16", "uibc", "clipboard", "file", "mirror-request", "file-browse", MediaPackets.PROTOCOL,
),
model = Build.MODEL,
resolution = "${size[0]}x${size[1]}",
@@ -326,7 +327,7 @@ class ReceiverSession(
}
continue
}
if (target.isNotEmpty() && transport == null) {
if ((target.isNotEmpty() || signalingUrl.isNotBlank()) && transport == null) {
val created = ReceiverTransport(
target,
41001,
@@ -1,6 +1,7 @@
package com.ttstd.lancast.receiver.discovery
import android.util.Log
import com.ttstd.lancast.receiver.session.SignalingEndpoint
import org.json.JSONArray
import org.json.JSONObject
import java.net.HttpURLConnection
@@ -62,7 +63,7 @@ class ReceiverAnnouncer(
private fun post(path: String, body: String): Boolean {
var connection: HttpURLConnection? = null
return try {
val http = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection
val http = SignalingEndpoint.connection(signalingUrl, path)
connection = http
http.requestMethod = "POST"
http.doOutput = true
@@ -15,7 +15,10 @@ import java.net.ServerSocket
import java.net.Socket
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import com.ttstd.lancast.receiver.util.Fingerprint
import java.util.concurrent.Executors
import java.util.concurrent.Semaphore
/**
* LocalSend 风格的文件服务(默认 53317,被占用时顺延)。
@@ -42,7 +45,8 @@ class FileHttpServer(
}
private val browser = FileBrowser(context)
private val workers = Executors.newCachedThreadPool()
private val workers = Executors.newFixedThreadPool(4)
private val clients = Semaphore(4)
private var serverSocket: ServerSocket? = null
private var acceptThread: Thread? = null
@@ -101,7 +105,13 @@ class FileHttpServer(
if (!running) return
continue
}
workers.execute { handle(client) }
if (!clients.tryAcquire()) { client.close(); continue }
try {
workers.execute { try { handle(client) } finally { clients.release() } }
} catch (_: java.util.concurrent.RejectedExecutionException) {
clients.release()
client.close()
}
}
}
@@ -127,9 +137,15 @@ class FileHttpServer(
}
}
val body = readBody(input, headers)
val path = target.substringBefore('?')
val query = parseQuery(target.substringAfter('?', ""))
val publicInfo = method == "GET" && path in setOf("/api/localsend/v1/info", "/api/localsend/v2/info")
val publicRegister = method == "POST" && path in setOf("/api/localsend/v1/register", "/api/localsend/v2/register")
if (!publicInfo && !publicRegister && !authorized(query, headers)) {
writeResponse(output, jsonResponse(403, "令牌无效"))
return
}
val body = if (publicInfo || publicRegister) byteArrayOf() else readBody(input, headers)
val response = try {
route(method, path, query, headers, body)
@@ -153,10 +169,10 @@ class FileHttpServer(
body: ByteArray,
): Response {
// LocalSend 发现/注册接口不需要令牌,方便桌面端识别设备。
if (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info") {
if (method == "GET" && (path == "/api/localsend/v1/info" || path == "/api/localsend/v2/info")) {
return jsonResponse(200, infoJson())
}
if (path.endsWith("/register")) {
if (method == "POST" && path in setOf("/api/localsend/v1/register", "/api/localsend/v2/register")) {
return Response(204, "application/json")
}
@@ -164,6 +180,9 @@ class FileHttpServer(
return jsonResponse(403, "令牌无效,请填写主界面显示的文件服务令牌")
}
val expectedMethod = if (path == "/mirror/request" || path.endsWith("/upload")) "POST" else "GET"
if (method != expectedMethod) return jsonResponse(405, "请求方法不支持")
return when (path) {
"/", "/index.html" -> htmlResponse(indexHtml())
"/browse" -> jsonResponse(200, browser.list(query["path"] ?: "").toString())
@@ -209,9 +228,11 @@ class FileHttpServer(
private fun authorized(query: Map<String, String>, headers: Map<String, String>): Boolean {
val expected = tokenProvider()
if (expected.isEmpty()) return true
if (expected.isBlank()) return false
val provided = query["token"] ?: headers["x-lancast-token"]
return provided == expected
return provided != null && MessageDigest.isEqual(
provided.toByteArray(Charsets.UTF_8), expected.toByteArray(Charsets.UTF_8),
)
}
private fun infoJson(): String = JSONObject().apply {
@@ -219,7 +240,7 @@ class FileHttpServer(
put("version", "2.1")
put("deviceModel", Build.MODEL ?: "Android")
put("deviceType", "mobile")
put("fingerprint", tokenProvider())
put("fingerprint", Fingerprint.of(context))
put("port", boundPort)
put("protocol", "http")
put("download", false)
@@ -288,7 +309,7 @@ class FileHttpServer(
var read = 0
while (read < buffer.size) {
val count = input.read(buffer, read, buffer.size - read)
if (count < 0) break
require(count >= 0) { "请求体未完整接收" }
read += count
}
return if (read == buffer.size) buffer else buffer.copyOf(read)
@@ -21,35 +21,50 @@ class FileService(
val sha256: String,
val token: String,
var offset: Long,
var complete: Boolean = false,
)
private data class Session(val id: String, val files: MutableMap<String, Entry>)
private data class Session(val id: String, val files: MutableMap<String, Entry>, var touched: Long = android.os.SystemClock.elapsedRealtime())
private val sessions = ConcurrentHashMap<String, Session>()
fun prepare(body: String): String {
@Synchronized fun prepare(body: String): String {
expire()
require(sessions.size < 8) { "文件会话过多,请稍后重试" }
root.mkdirs()
val request = JSONObject(body)
val files = request.getJSONArray("files")
require(files.length() in 1..32) { "文件数量必须为 1~32" }
val sessionId = UUID.randomUUID().toString()
val entries = mutableMapOf<String, Entry>()
val tokens = JSONObject()
val rejected = JSONArray()
var totalSize = 0L
for (index in 0 until files.length()) {
val file = files.getJSONObject(index)
val id = file.getString("id")
val name = safeName(file.getString("name"))
require(entries.values.none { it.name == name }) { "同一会话不能包含重名文件" }
val size = file.getLong("size")
require(size in 0..(64L * 1024 * 1024)) { "单文件不能超过 64 MiB" }
totalSize += size
require(totalSize <= 64L * 1024 * 1024) { "单次传输不能超过 64 MiB" }
require(id.isNotBlank() && !entries.containsKey(id)) { "文件 ID 无效或重复" }
val hash = file.optString("sha256", "")
val target = File(root, "$sessionId-$name")
require(hash.isEmpty() || hash.matches(Regex("[0-9a-fA-F]{64}"))) { "SHA-256 格式无效" }
val token = UUID.randomUUID().toString()
val alreadyThere = target.exists() && target.length() == size && sha256(target) == hash
entries[id] = Entry(id, name, size, hash, token, if (alreadyThere) size else 0)
entries[id] = Entry(id, name, size, hash, token, 0)
tokens.put(id, token)
}
sessions[sessionId] = Session(sessionId, entries)
try {
entries.values.filter { it.size == 0L }.forEach { entry ->
File(root, "$sessionId-${entry.name}.part").writeBytes(byteArrayOf())
finish(sessionId, entry)
}
} catch (error: Exception) { cancel(sessionId); throw error }
return JSONObject().apply {
put("sessionId", sessionId)
put("tokens", tokens)
@@ -57,20 +72,26 @@ class FileService(
}.toString()
}
fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int {
val entry = sessions[sessionId]?.files?.get(fileId)
@Synchronized fun writeChunk(sessionId: String, fileId: String, token: String, offset: Long, bytes: ByteArray): Int {
expire()
val session = sessions[sessionId] ?: throw IllegalArgumentException("文件会话已过期")
val entry = session.files[fileId]
?: throw IllegalArgumentException("未知文件会话")
if (entry.token != token) throw SecurityException("文件令牌不匹配")
val target = File(root, "$sessionId-${entry.name}")
require(!entry.complete && offset == entry.offset && offset >= 0 && bytes.isNotEmpty() && bytes.size <= 256 * 1024 && bytes.size.toLong() <= entry.size - offset) { "分片偏移或大小无效" }
val target = File(root, "$sessionId-${entry.name}.part")
RandomAccessFile(target, "rw").use { file ->
file.seek(offset)
file.write(bytes)
}
entry.offset = maxOf(entry.offset, offset + bytes.size)
session.touched = android.os.SystemClock.elapsedRealtime()
if (entry.offset == entry.size) finish(sessionId, entry)
return bytes.size
}
fun progress(sessionId: String): String {
@Synchronized fun progress(sessionId: String): String {
expire()
val session = sessions[sessionId] ?: return JSONObject().put("files", JSONArray()).toString()
val array = JSONArray()
session.files.values.forEach { entry ->
@@ -83,8 +104,25 @@ class FileService(
return JSONObject().put("sessionId", sessionId).put("files", array).toString()
}
fun cancel(sessionId: String) {
sessions.remove(sessionId)
@Synchronized fun cancel(sessionId: String) {
sessions.remove(sessionId)?.files?.values?.forEach { entry ->
File(root, "$sessionId-${entry.name}.part").delete()
}
}
private fun expire() {
val cutoff = android.os.SystemClock.elapsedRealtime() - 15 * 60 * 1000
sessions.values.filter { it.touched < cutoff }.forEach { cancel(it.id) }
}
private fun finish(sessionId: String, entry: Entry) {
val partial = File(root, "$sessionId-${entry.name}.part")
if (entry.sha256.isNotEmpty() && !sha256(partial).equals(entry.sha256, ignoreCase = true)) {
cancel(sessionId)
throw IllegalArgumentException("文件 SHA-256 校验失败,已清理临时文件")
}
check(partial.renameTo(File(root, "$sessionId-${entry.name}"))) { "文件保存失败" }
entry.complete = true
}
/** 控制通道 msgType=7 的 `op=list`:浏览 Android 文件目录。 */
@@ -2,10 +2,18 @@ package com.ttstd.lancast.receiver.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicLong
import javax.crypto.Mac
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
object MediaPackets {
const val PROTOCOL = "aes-gcm/2"
const val OVERHEAD = 65
private val packetSequence = AtomicLong(1)
private val frameSequence = AtomicLong(1)
fun nextFrameId(): Long = frameSequence.getAndIncrement().also { check(it > 0) { "媒体帧计数耗尽" } }
const val FLAG_KEYFRAME = 1
const val FLAG_AUDIO = 2
// 与 Rust Core 的 media::stream 保持一致的扩展标志位。
@@ -16,21 +24,39 @@ object MediaPackets {
const val FLAG_FRAGMENT_START = 0x10
const val FLAG_FRAGMENT_CONTINUE = 0x20
const val FLAG_FRAGMENT_END = 0x40
// 单个 UDP 分片的负载上限:13 字节头 + 4 字节 MAC + 1200 负载仍远小于 MTU。
const val FRAGMENT_PAYLOAD_SIZE = 1200
private const val HEADER_SIZE = 13
private const val MAC_SIZE = 4
// 1152 + 65 + IPv6/UDP 48 = 1265,低于 IPv6 最小 MTU 1280。
const val FRAGMENT_PAYLOAD_SIZE = 1152
private const val HEADER_SIZE = 37
fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray): ByteArray {
fun encode(payload: ByteArray, pts: Long, flags: Int, sessionKey: ByteArray,
frameId: Long = nextFrameId(), fragmentIndex: Int = 0, fragmentCount: Int = 1): ByteArray {
require(payload.size <= FRAGMENT_PAYLOAD_SIZE && fragmentCount in 1..8192 && fragmentIndex in 0 until fragmentCount && frameId > 0)
val sequence = packetSequence.getAndIncrement()
check(sequence > 0) { "媒体 nonce 计数耗尽,必须重启并重新握手" }
val header = ByteBuffer.allocate(HEADER_SIZE).order(ByteOrder.LITTLE_ENDIAN).apply {
putLong(pts)
put("TTM2".toByteArray(Charsets.US_ASCII))
put(flags.toByte())
putLong(pts)
putLong(sequence)
putLong(frameId)
putShort(fragmentIndex.toShort())
putShort(fragmentCount.toShort())
putInt(payload.size)
}.array()
val signed = header + payload
val mac = Mac.getInstance("HmacSHA256").apply {
init(SecretKeySpec(sessionKey, "HmacSHA256"))
}.doFinal(signed)
return signed + mac.copyOf(MAC_SIZE)
val nonce = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN).apply {
put("and2".toByteArray(Charsets.US_ASCII)); putLong(sequence)
}.array()
// Domain separation from the outer relay-media AES-GCM key.
val prk = hmac("ttstdconnect-v1".toByteArray(Charsets.UTF_8), sessionKey)
val key = hmac(prk, "lancast/media/packet/v2".toByteArray(Charsets.UTF_8) + byteArrayOf(1))
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
updateAAD(header)
}
return header + nonce + cipher.doFinal(payload)
}
private fun hmac(key: ByteArray, bytes: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").apply {
init(SecretKeySpec(key, "HmacSHA256"))
}.doFinal(bytes)
}
@@ -152,12 +152,10 @@ class ReceiverTransport(
/** 当前生效的权限等级:`min(主控端请求, 本机上限)`。 */
@Volatile
var access: Int = AccessLevel.FULL
var access: Int = AccessLevel.VIEW
private set
@Volatile var mediaProtocolReady: Boolean = false
private set
/** 已回送过的最新等级,避免每帧回一次应答。 */
@Volatile
private var reportedAccess: Int = -1
/** 因权限不足丢弃的事件计数,只用于日志去抖。 */
@Volatile
@@ -183,6 +181,10 @@ class ReceiverTransport(
executor.execute {
var retryDelayMs = INITIAL_RETRY_MS
while (active) {
if (host.isBlank()) {
sleepQuietly(500)
continue
}
if (relayMode) {
sleepQuietly(300)
continue
@@ -280,6 +282,7 @@ class ReceiverTransport(
}
udp = DatagramSocket()
resetAccess()
running = true
consecutiveFailures = 0
Log.i(TAG, "已连接主控端 $host:$controlPort")
@@ -348,6 +351,7 @@ class ReceiverTransport(
fun sendControl(event: ControlEvent) {
executor.execute {
if (event is ControlEvent.Clipboard && access < AccessLevel.CONTROL) return@execute
val key = keys?.control ?: return@execute
if (!running) return@execute
val frame = ControlFrames.encode(event, sequence++)
@@ -357,7 +361,7 @@ class ReceiverTransport(
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo, hevc: Boolean = false) {
val key = keys?.video ?: return
if (!running) return
if (!running || !mediaProtocolReady) return
val duplicate = buffer.duplicate().apply {
position(info.offset)
limit(info.offset + info.size)
@@ -372,9 +376,12 @@ class ReceiverTransport(
if (hevc) flags = flags or MediaPackets.FLAG_HEVC
val target = InetSocketAddress(host, mediaPort)
val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE
val frameId = MediaPackets.nextFrameId()
val fragmentCount = (payload.size + chunk - 1) / chunk
if (payload.size > 8 * 1024 * 1024) return
try {
if (payload.size <= chunk) {
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key)
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key, frameId)
dispatchMedia(true, packet, target)
return
}
@@ -392,7 +399,7 @@ class ReceiverTransport(
fragmentFlags = fragmentFlags or MediaPackets.FLAG_FRAGMENT_END
}
val part = payload.copyOfRange(offset, end)
val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key)
val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key, frameId, offset / chunk, fragmentCount)
dispatchMedia(true, packet, target)
offset = end
}
@@ -403,10 +410,16 @@ class ReceiverTransport(
/** 发送一段 PCM16(48 kHz 双声道);主控端直接播放,不做解码。 */
fun sendAudio(pcm: ByteArray, pts: Long) {
val key = keys?.audio ?: return
if (!running) return
if (!running || !mediaProtocolReady || pcm.isEmpty() || pcm.size > 8 * 1024 * 1024) return
val flags = MediaPackets.FLAG_AUDIO or MediaPackets.FLAG_PCM
val packet = MediaPackets.encode(pcm, pts, flags, key)
dispatchMedia(false, packet, InetSocketAddress(host, audioPort))
val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE
val count = (pcm.size + chunk - 1) / chunk
val frameId = MediaPackets.nextFrameId()
for (index in 0 until count) {
val part = pcm.copyOfRange(index * chunk, minOf(pcm.size, (index + 1) * chunk))
val packet = MediaPackets.encode(part, pts, flags, key, frameId, index, count)
dispatchMedia(false, packet, InetSocketAddress(host, audioPort))
}
}
/**
@@ -527,7 +540,9 @@ class ReceiverTransport(
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
is ControlEvent.Pong -> Unit
// 中继模式同样支持投屏:媒体分片走 `media` 消息(已加密)。
is ControlEvent.Mirror -> onMirrorEvent?.invoke(event.action, event.message)
is ControlEvent.Mirror -> if (event.action == 0 && !mediaProtocolReady) {
sendMirror(5, "媒体协议不兼容,需要 ${MediaPackets.PROTOCOL},请更新主控端")
} else onMirrorEvent?.invoke(event.action, event.message)
is ControlEvent.SessionConfig -> {
applyAccessRequest(event.json)
onSessionConfig?.invoke(event.json)
@@ -550,9 +565,19 @@ class ReceiverTransport(
* 有效等级永远不超过 [maxAccess],结果变化时回送一次 msgType=10 应答,
* 主控端据此把超出权限的操作禁掉。
*/
private fun resetAccess() {
access = AccessLevel.VIEW
mediaProtocolReady = false
}
private fun applyAccessRequest(json: String) {
val requested = try {
AccessLevel.parse(JSONObject(json).optString("access"), access)
val config = JSONObject(json)
mediaProtocolReady = config.optString("mediaProtocol") == MediaPackets.PROTOCOL
if (!mediaProtocolReady) {
onMirrorEvent?.invoke(1, "媒体协议不兼容")
}
AccessLevel.parse(config.optString("access"), access)
} catch (_: Exception) {
return
}
@@ -561,17 +586,19 @@ class ReceiverTransport(
access = next
Log.i(TAG, "权限等级 ${AccessLevel.name(next)}(请求 ${AccessLevel.name(requested)},上限 ${AccessLevel.name(maxAccess)})")
}
if (next != reportedAccess) sendAccessReply(next)
// 每次配置均确认,避免主控端重置 UI 后因等级未变化而等不到应答。
sendAccessReply(next)
}
/** 主动回送当前有效等级(首次连接、上限调整、主控端重新请求时)。 */
fun sendAccessReply(level: Int = access) {
reportedAccess = level
val payload = JSONObject()
.put("level", level)
.put("name", AccessLevel.name(level))
.put("max", maxAccess)
.put("requested", level)
.put("mediaProtocol", if (mediaProtocolReady) MediaPackets.PROTOCOL else "")
.put("supportedMediaProtocols", org.json.JSONArray().put(MediaPackets.PROTOCOL))
sendControl(ControlEvent.Access(payload.toString()))
}
@@ -668,6 +695,7 @@ class ReceiverTransport(
relayClient = client
crypto = sessionCrypto
keys = sessionKeys
resetAccess()
running = true
consecutiveFailures = 0
Log.i(TAG, "已通过中继连接 $peerId")
@@ -34,7 +34,11 @@ class RelayClient(
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)
val message = messages.optJSONObject(index) ?: continue
val payload = message.optJSONObject("payload") ?: continue
if (message.optString("to") != deviceId || message.optString("from").isEmpty() ||
payload.optString("from") != message.optString("from")) continue
result.add(payload)
}
return result
}
@@ -82,7 +86,7 @@ class RelayClient(
}
private fun request(method: String, path: String, body: String?): String {
val connection = URL(base + path).openConnection() as HttpURLConnection
val connection = SignalingEndpoint.connection(base, path)
return try {
connection.requestMethod = method
connection.connectTimeout = timeoutMs
@@ -95,8 +95,8 @@ class SessionCrypto {
/**
* 中继媒体分片加密:输出 = 12 字节随机 nonce + 密文 + 16 字节 tag。
*
* 直连时媒体走 UDP,只有局域网可见;经信令服务器转发必须再套一层,
* 否则服务器能直接看到画面。AAD 固定 `relay-media`,与 Rust 侧解密保持一致。
* 内层 MediaPackets v2 已加密;中继保留独立外层,使用基础媒体密钥,
* 内层使用派生包密钥,两层 nonce 空间隔离。AAD 与 Rust 对齐为 `relay-media`。
*/
fun encodeRelayMedia(packet: ByteArray, key: ByteArray): ByteArray {
val nonce = ByteArray(12).also { RELAY_NONCE_RANDOM.nextBytes(it) }
@@ -0,0 +1,22 @@
package com.ttstd.lancast.receiver.session
import android.net.Uri
import java.net.HttpURLConnection
import java.net.URL
/** Internal fragments never leave the client; all network auth uses a header. */
object SignalingEndpoint {
fun connection(base: String, path: String): HttpURLConnection {
val uri = Uri.parse(base.trim())
require(uri.scheme == "https" || uri.scheme == "http") { "信令地址必须为 http/https" }
val fragment = uri.encodedFragment.orEmpty()
val token = if (fragment.startsWith("token=")) Uri.decode(fragment.substring(6)) else ""
require(token.none { it <= ' ' || it >= '\u007f' }) { "信令令牌包含非法字符" }
val clean = uri.buildUpon().fragment(null).build().toString().trimEnd('/')
return (URL(clean + path).openConnection() as HttpURLConnection).apply {
// Do not forward credentials to redirects, including HTTPS -> HTTP.
instanceFollowRedirects = false
if (token.isNotEmpty()) setRequestProperty("Authorization", "Bearer $token")
}
}
}