feat: 接入端到端 demo 与签名变体

- Flutter 桌面端通过 dart:ffi 调用 Rust Core cdylib
- 实现 ECDH P-256 密钥协商、HKDF 子密钥派生、AES-256-GCM 控制帧
- Android 被控端用派生密钥做控制帧加密与媒体包 MAC
- 新增 libopus JNI 骨架,默认回退 MediaCodec
- 新增 aosp/zhanxun/neutral 签名变体与系统 sharedUserId
- 本机独立信令服务与设置页开关
- 新增 .gitignore 排除所有编译产物与打包目录
This commit is contained in:
tongtong committed 2026-11-26 18:24:02 +08:00
commit 31b9a52eb4
154 files changed
+13287

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
use crate::json::JsonValue;
use super::DiscoveryError;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceInfo {
pub device_id: String,
pub name: String,
pub ip: String,
pub media_port: u16,
pub control_port: u16,
pub fingerprint: String,
pub capabilities: Vec<String>,
pub model: String,
pub resolution: String,
pub signaling_url: Option<String>,
}
impl DeviceInfo {
pub fn from_json(value: &JsonValue) -> Result<Self, DiscoveryError> {
let device_id = required_string(value, "deviceId")
.or_else(|| required_string(value, "id"))
.ok_or(DiscoveryError::InvalidRecord("缺少 deviceId"))?;
let ip = required_string(value, "ip").ok_or(DiscoveryError::InvalidRecord("缺少 ip"))?;
let fingerprint = required_string(value, "fp")
.or_else(|| required_string(value, "fingerprint"))
.ok_or(DiscoveryError::InvalidRecord("缺少证书指纹 fp"))?;
let media_port = port_from(value, "mediaPort")?;
let control_port = port_from(value, "controlPort")?;
let capabilities = value
.get("cap")
.and_then(JsonValue::as_array)
.map(|values| {
values
.iter()
.filter_map(JsonValue::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default();
let name = required_string(value, "name").unwrap_or_else(|| device_id.clone());
Ok(Self {
device_id,
name,
ip,
media_port,
control_port,
fingerprint,
capabilities,
model: required_string(value, "model").unwrap_or_default(),
resolution: required_string(value, "res").unwrap_or_default(),
signaling_url: required_string(value, "sig"),
})
}
pub fn to_register_json(&self, ttl: u64) -> JsonValue {
let mut value = JsonValue::object();
value.insert("deviceId", JsonValue::from(self.device_id.as_str()));
value.insert("name", JsonValue::from(self.name.as_str()));
value.insert("ip", JsonValue::from(self.ip.as_str()));
value.insert("mediaPort", JsonValue::from(self.media_port as u64));
value.insert("controlPort", JsonValue::from(self.control_port as u64));
value.insert("fp", JsonValue::from(self.fingerprint.as_str()));
value.insert(
"cap",
JsonValue::Array(self.capabilities.iter().map(JsonValue::from).collect()),
);
value.insert("ttl", JsonValue::from(ttl));
value.insert("model", JsonValue::from(self.model.as_str()));
value.insert("res", JsonValue::from(self.resolution.as_str()));
if let Some(url) = &self.signaling_url {
value.insert("sig", JsonValue::from(url.as_str()));
}
value
}
pub fn supports(&self, capability: &str) -> bool {
self.capabilities.iter().any(|item| item == capability)
}
}
fn required_string(value: &JsonValue, key: &str) -> Option<String> {
value
.get(key)
.and_then(JsonValue::as_str)
.filter(|text| !text.is_empty())
.map(str::to_string)
}
fn port_from(value: &JsonValue, key: &str) -> Result<u16, DiscoveryError> {
let number = value
.get(key)
.and_then(JsonValue::as_u64)
.ok_or_else(|| DiscoveryError::InvalidRecord("端口字段无效"))?;
if number == 0 || number > u16::MAX as u64 {
return Err(DiscoveryError::InvalidRecord("端口超出范围"));
}
Ok(number as u16)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::json::parse;
#[test]
fn device_from_signaling_payload() {
let raw = r#"{"deviceId":"uuid-1","name":"客厅Pixel","ip":"192.168.1.10",
"mediaPort":41000,"controlPort":41001,"fp":"sha256:ab12","cap":["h264","opus"]}"#;
let device = DeviceInfo::from_json(&parse(raw).unwrap()).unwrap();
assert_eq!(device.name, "客厅Pixel");
assert_eq!(device.media_port, 41000);
assert!(device.supports("opus"));
}
#[test]
fn invalid_port_is_rejected() {
let raw = r#"{"deviceId":"a","ip":"1.2.3.4","fp":"f","mediaPort":0,"controlPort":1}"#;
assert!(DeviceInfo::from_json(&parse(raw).unwrap()).is_err());
}
}
+270
View File
@@ -0,0 +1,270 @@
use std::time::{Duration, Instant};
use mdns_sd::{ResolvedService, ServiceDaemon, ServiceEvent, ServiceInfo};
use super::{DeviceInfo, DiscoveryError};
pub const SERVICE_TYPE: &str = "_lancast._tcp.local.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MdnsTxt {
pub txtvers: u8,
pub ver: u8,
pub dev: String,
pub capabilities: Vec<String>,
pub resolution: String,
pub model: String,
pub fingerprint: String,
pub signaling_url: Option<String>,
pub media_port: Option<u16>,
}
impl MdnsTxt {
pub fn new(fingerprint: impl Into<String>, capabilities: &[&str]) -> Self {
Self {
txtvers: 1,
ver: 1,
dev: "android".to_string(),
capabilities: capabilities.iter().map(|item| item.to_string()).collect(),
resolution: "1920x1080".to_string(),
model: String::new(),
fingerprint: fingerprint.into(),
signaling_url: None,
media_port: None,
}
}
pub fn to_records(&self) -> Vec<String> {
let mut records = vec![
format!("txtvers={}", self.txtvers),
format!("ver={}", self.ver),
format!("dev={}", self.dev),
format!("cap={}", self.capabilities.join(",")),
format!("res={}", self.resolution),
format!("model={}", self.model),
format!("fp={}", self.fingerprint),
];
if let Some(url) = &self.signaling_url {
records.push(format!("sig={}", url));
}
if let Some(port) = self.media_port {
records.push(format!("mport={}", port));
}
records
}
pub fn parse_records(records: &[String]) -> Result<Self, DiscoveryError> {
let mut result = Self {
txtvers: 0,
ver: 0,
dev: String::new(),
capabilities: Vec::new(),
resolution: String::new(),
model: String::new(),
fingerprint: String::new(),
signaling_url: None,
media_port: None,
};
for record in records {
let (key, value) = record
.split_once('=')
.ok_or(DiscoveryError::InvalidRecord("TXT 记录缺少 '='"))?;
match key {
"txtvers" => result.txtvers = parse_u8(value)?,
"ver" => result.ver = parse_u8(value)?,
"dev" => result.dev = value.to_string(),
"cap" => {
result.capabilities = value
.split(',')
.filter(|item| !item.is_empty())
.map(str::to_string)
.collect()
}
"res" => result.resolution = value.to_string(),
"model" => result.model = value.to_string(),
"fp" => result.fingerprint = value.to_string(),
"sig" => result.signaling_url = Some(value.to_string()),
"mport" => result.media_port = Some(parse_u16(value)?),
_ => {}
}
}
if result.txtvers != 1 || result.ver != 1 {
return Err(DiscoveryError::InvalidRecord("不支持的 TXT/协议版本"));
}
if result.fingerprint.is_empty() {
return Err(DiscoveryError::InvalidRecord("TXT 记录缺少证书指纹"));
}
Ok(result)
}
pub fn into_device(
self,
device_id: String,
ip: String,
control_port: u16,
media_port: u16,
) -> DeviceInfo {
DeviceInfo {
device_id,
name: if self.model.is_empty() {
ip.clone()
} else {
self.model.clone()
},
ip,
media_port: self.media_port.unwrap_or(media_port),
control_port,
fingerprint: self.fingerprint,
capabilities: self.capabilities,
model: self.model,
resolution: self.resolution,
signaling_url: self.signaling_url,
}
}
}
fn parse_u8(value: &str) -> Result<u8, DiscoveryError> {
value
.parse::<u8>()
.map_err(|_| DiscoveryError::InvalidRecord("版本号不是合法数字"))
}
fn parse_u16(value: &str) -> Result<u16, DiscoveryError> {
value
.parse::<u16>()
.map_err(|_| DiscoveryError::InvalidRecord("端口不是合法数字"))
}
pub trait DeviceDiscovery: Send {
fn browse(&mut self, timeout: Duration) -> Result<Vec<DeviceInfo>, DiscoveryError>;
}
#[derive(Debug, Default)]
pub struct StaticDiscovery {
devices: Vec<DeviceInfo>,
}
impl StaticDiscovery {
pub fn new(devices: Vec<DeviceInfo>) -> Self {
Self { devices }
}
}
impl DeviceDiscovery for StaticDiscovery {
fn browse(&mut self, _timeout: Duration) -> Result<Vec<DeviceInfo>, DiscoveryError> {
Ok(self.devices.clone())
}
}
pub trait MdnsAdapter: Send {
fn browse_devices(&self, timeout: Duration) -> Result<Vec<DeviceInfo>, DiscoveryError>;
fn advertise(&self, device: &DeviceInfo) -> Result<(), DiscoveryError>;
}
pub struct NativeMdnsAdapter {
daemon: ServiceDaemon,
}
impl NativeMdnsAdapter {
pub fn new() -> Result<Self, DiscoveryError> {
Ok(Self {
daemon: ServiceDaemon::new().map_err(|error| DiscoveryError::Mdns(error.to_string()))?,
})
}
}
impl MdnsAdapter for NativeMdnsAdapter {
fn browse_devices(&self, timeout: Duration) -> Result<Vec<DeviceInfo>, DiscoveryError> {
let receiver = self
.daemon
.browse(SERVICE_TYPE)
.map_err(|error| DiscoveryError::Mdns(error.to_string()))?;
let deadline = Instant::now() + timeout;
let mut devices: Vec<DeviceInfo> = Vec::new();
while let Ok(event) = receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
if let ServiceEvent::ServiceResolved(service) = event {
if let Some(device) = device_from_resolved(&service) {
if !devices.iter().any(|existing| existing.device_id == device.device_id) {
devices.push(device);
}
}
}
}
let _ = self.daemon.stop_browse(SERVICE_TYPE);
Ok(devices)
}
fn advertise(&self, device: &DeviceInfo) -> Result<(), DiscoveryError> {
let capabilities: Vec<&str> = device.capabilities.iter().map(String::as_str).collect();
let mut txt = MdnsTxt::new(&device.fingerprint, &capabilities);
txt.model = device.model.clone();
txt.resolution = device.resolution.clone();
txt.media_port = Some(device.media_port);
txt.signaling_url = device.signaling_url.clone();
let properties: Vec<(String, String)> = txt
.to_records()
.iter()
.filter_map(|record| {
record.split_once('=').map(|(key, value)| (key.to_string(), value.to_string()))
})
.collect();
let ip = device
.ip
.parse::<std::net::Ipv4Addr>()
.map_err(|_| DiscoveryError::InvalidRecord("mDNS 广播需要 IPv4 地址"))?;
let service = ServiceInfo::new(
SERVICE_TYPE,
&device.device_id,
"lancast.local.",
std::net::IpAddr::V4(ip),
device.control_port,
&properties[..],
)
.map_err(|error| DiscoveryError::Mdns(error.to_string()))?;
self.daemon
.register(service)
.map_err(|error| DiscoveryError::Mdns(error.to_string()))
}
}
fn device_from_resolved(service: &ResolvedService) -> Option<DeviceInfo> {
let ip = service.get_addresses_v4().into_iter().next()?.to_string();
let records: Vec<String> = service
.get_properties()
.iter()
.map(|property| format!("{}={}", property.key(), property.val_str()))
.collect();
let txt = MdnsTxt::parse_records(&records).ok()?;
let device_id = mdns_sd::instance_name_unescaped(service.get_fullname());
let control_port = service.get_port();
Some(txt.into_device(device_id, ip, control_port, control_port.saturating_add(1)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn txt_record_roundtrip() {
let txt = MdnsTxt::new("sha256:ab12cd34", &["h264", "opus"]);
let records = txt.to_records();
let parsed = MdnsTxt::parse_records(&records).unwrap();
assert_eq!(parsed, txt);
}
#[test]
fn media_port_record_roundtrip() {
let mut txt = MdnsTxt::new("sha256:ab12cd34", &["h264"]);
txt.media_port = Some(41000);
let parsed = MdnsTxt::parse_records(&txt.to_records()).unwrap();
assert_eq!(parsed.media_port, Some(41000));
}
#[test]
fn reject_missing_fingerprint() {
let records = vec!["txtvers=1".into(), "ver=1".into(), "cap=h264".into()];
assert!(MdnsTxt::parse_records(&records).is_err());
}
}
+50
View File
@@ -0,0 +1,50 @@
pub mod device;
pub mod mdns;
pub mod signaling;
use std::fmt;
use crate::json::JsonError;
pub use device::DeviceInfo;
pub use mdns::{DeviceDiscovery, MdnsAdapter, MdnsTxt, NativeMdnsAdapter, StaticDiscovery, SERVICE_TYPE};
pub use signaling::SignalingClient;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiscoveryError {
InvalidUrl(&'static str),
InvalidRecord(&'static str),
Http(String),
Io(String),
Json(JsonError),
Mdns(String),
Unsupported(&'static str),
}
impl fmt::Display for DiscoveryError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidUrl(reason) => write!(formatter, "信令地址无效:{}", reason),
Self::InvalidRecord(reason) => write!(formatter, "发现记录无效:{}", reason),
Self::Http(reason) => write!(formatter, "信令请求失败:{}", reason),
Self::Io(reason) => write!(formatter, "网络 I/O 失败:{}", reason),
Self::Json(error) => write!(formatter, "信令 JSON 解析失败:{}", error),
Self::Mdns(reason) => write!(formatter, "mDNS 失败:{}", reason),
Self::Unsupported(reason) => write!(formatter, "当前实现尚不支持:{}", reason),
}
}
}
impl std::error::Error for DiscoveryError {}
impl From<JsonError> for DiscoveryError {
fn from(error: JsonError) -> Self {
Self::Json(error)
}
}
impl From<std::io::Error> for DiscoveryError {
fn from(error: std::io::Error) -> Self {
Self::Io(error.to_string())
}
}
+223
View File
@@ -0,0 +1,223 @@
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use crate::json::{self, JsonValue};
use super::{DeviceInfo, DiscoveryError};
#[derive(Debug, Clone)]
struct Endpoint {
host: String,
authority: String,
port: u16,
prefix: String,
}
#[derive(Debug, Clone)]
pub struct SignalingClient {
endpoint: Endpoint,
timeout: Duration,
}
impl SignalingClient {
pub fn new(base_url: impl Into<String>, timeout: Duration) -> Result<Self, DiscoveryError> {
Ok(Self {
endpoint: parse_endpoint(&base_url.into())?,
timeout,
})
}
pub fn register(&self, device: &DeviceInfo, ttl: u64) -> Result<(), DiscoveryError> {
let body = device.to_register_json(ttl).encode();
let response = self.send_request("POST", "/register", Some(&body))?;
let value = json::parse(&response)?;
if value.get("ok").and_then(JsonValue::as_bool) == Some(false) {
return Err(DiscoveryError::Http("信令服务器拒绝注册".to_string()));
}
Ok(())
}
pub fn list(&self) -> Result<Vec<DeviceInfo>, DiscoveryError> {
let response = self.send_request("GET", "/list", None)?;
let value = json::parse(&response)?;
let devices = value
.get("devices")
.and_then(JsonValue::as_array)
.or_else(|| value.as_array())
.ok_or(DiscoveryError::InvalidRecord("/list 响应缺少 devices 数组"))?;
devices.iter().map(DeviceInfo::from_json).collect()
}
pub fn heartbeat(&self, device_id: &str) -> Result<(), DiscoveryError> {
let mut body = JsonValue::object();
body.insert("deviceId", JsonValue::from(device_id));
self.send_request("POST", "/heartbeat", Some(&body.encode()))?;
Ok(())
}
pub fn send_relay(
&self,
from: &str,
to: &str,
payload: &JsonValue,
) -> Result<(), DiscoveryError> {
let mut body = JsonValue::object();
body.insert("from", JsonValue::from(from));
body.insert("to", JsonValue::from(to));
body.insert("payload", payload.clone());
self.send_request("POST", "/relay", Some(&body.encode()))?;
Ok(())
}
pub fn poll_relay(&self, device_id: &str) -> Result<Vec<JsonValue>, DiscoveryError> {
let path = format!("/relay/poll?deviceId={}", crate::util::url_encode(device_id));
let response = self.send_request("GET", &path, None)?;
let value = json::parse(&response)?;
Ok(value
.get("messages")
.and_then(JsonValue::as_array)
.unwrap_or_default()
.to_vec())
}
fn send_request(
&self,
method: &str,
path: &str,
body: Option<&str>,
) -> Result<String, DiscoveryError> {
let address = (self.endpoint.host.as_str(), self.endpoint.port)
.to_socket_addrs()?
.next()
.ok_or(DiscoveryError::InvalidUrl("无法解析信令服务器地址"))?;
let mut stream = TcpStream::connect_timeout(&address, self.timeout)?;
stream.set_read_timeout(Some(self.timeout))?;
stream.set_write_timeout(Some(self.timeout))?;
let body = body.unwrap_or("");
let full_path = if self.endpoint.prefix.is_empty() {
path.to_string()
} else {
format!("{}{}", self.endpoint.prefix, path)
};
let request = format!(
"{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{}",
method, full_path, self.endpoint.authority, body.len(), body
);
stream.write_all(request.as_bytes())?;
stream.flush()?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
let (headers, raw_body) = response
.split_once("\r\n\r\n")
.ok_or_else(|| DiscoveryError::Http("信令响应缺少头部分隔符".to_string()))?;
let status_line = headers
.lines()
.next()
.ok_or_else(|| DiscoveryError::Http("信令响应缺少状态行".to_string()))?;
let status_code = status_line
.split_whitespace()
.nth(1)
.and_then(|code| code.parse::<u16>().ok())
.ok_or_else(|| DiscoveryError::Http("信令响应状态码无效".to_string()))?;
if status_code >= 400 {
return Err(DiscoveryError::Http(format!(
"HTTP {} {}",
status_code,
raw_body.trim()
)));
}
if headers
.lines()
.any(|line| line.to_ascii_lowercase().contains("transfer-encoding: chunked"))
{
decode_chunked(raw_body)
} else {
Ok(raw_body.to_string())
}
}
}
fn parse_endpoint(base_url: &str) -> Result<Endpoint, DiscoveryError> {
let rest = base_url
.strip_prefix("http://")
.ok_or(DiscoveryError::InvalidUrl("当前版本仅支持 http://,HTTPS 由平台网络栈处理"))?;
let (authority, path) = match rest.find('/') {
Some(index) => (&rest[..index], &rest[index..]),
None => (rest, ""),
};
if authority.is_empty() {
return Err(DiscoveryError::InvalidUrl("缺少主机名"));
}
let (host, port) = if let Some(inner) = authority.strip_prefix('[').and_then(|v| v.strip_suffix(']')) {
let port = authority
.rsplit_once(':')
.and_then(|(_, value)| value.parse::<u16>().ok())
.ok_or(DiscoveryError::InvalidUrl("IPv6 地址缺少合法端口"))?;
(inner.to_string(), port)
} else if let Some((host, raw_port)) = authority.rsplit_once(':') {
let port = raw_port
.parse::<u16>()
.map_err(|_| DiscoveryError::InvalidUrl("端口号不是合法数字"))?;
(host.to_string(), port)
} else {
(authority.to_string(), 80)
};
if host.is_empty() {
return Err(DiscoveryError::InvalidUrl("主机名为空"));
}
Ok(Endpoint {
host,
authority: authority.to_string(),
port,
prefix: path.trim_end_matches('/').to_string(),
})
}
fn decode_chunked(raw: &str) -> Result<String, DiscoveryError> {
let bytes = raw.as_bytes();
let mut position = 0;
let mut output = Vec::new();
loop {
let relative_end = bytes[position..]
.windows(2)
.position(|window| window == b"\r\n")
.ok_or_else(|| DiscoveryError::Http("分块响应格式错误".to_string()))?;
let line_end = position + relative_end;
let size_line = std::str::from_utf8(&bytes[position..line_end])
.map_err(|_| DiscoveryError::Http("分块长度不是 UTF-8".to_string()))?;
let size_text = size_line.split(';').next().unwrap_or("").trim();
let size = usize::from_str_radix(size_text, 16)
.map_err(|_| DiscoveryError::Http("分块长度不是十六进制".to_string()))?;
position = line_end + 2;
if size == 0 {
break;
}
if position + size > bytes.len() {
return Err(DiscoveryError::Http("分块内容不完整".to_string()));
}
output.extend_from_slice(&bytes[position..position + size]);
position += size + 2;
}
String::from_utf8(output).map_err(|_| DiscoveryError::Http("响应内容不是 UTF-8".to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_base_url() {
let endpoint = parse_endpoint("http://127.0.0.1:8080/api/").unwrap();
assert_eq!(endpoint.host, "127.0.0.1");
assert_eq!(endpoint.port, 8080);
assert_eq!(endpoint.prefix, "/api");
}
#[test]
fn decode_chunked_body() {
assert_eq!(decode_chunked("5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n").unwrap(), "hello world");
}
}