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

+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");
}
}