- 支持 Ctrl+V 粘贴配对文本和二维码图片,预览确认后识别校验 - 修复控制发送阻塞、TLS 读写争锁、设备切换沿用旧连接及串流误关窗 - 优化媒体加密上下文、UDP 接收缓冲和异步诊断日志 - 安装器按路径停止主控与信令进程,统一递增版本、打包和清理旧产物 - 发布 0.1.3+4,通过三端编译、20 项 Flutter 测试和 58 项 Rust 单元测试
1497 lines
56 KiB
Rust
1497 lines
56 KiB
Rust
//! 可运行的本机 demo 服务端。
|
||
//!
|
||
//! 协议(demo v1,控制通道不叠加 TLS,保密性由 AES-GCM 控制帧保证):
|
||
//! 1. 被控端反连 TCP 41001,先发送 65 字节 ECDH P-256 公钥。
|
||
//! 2. 主控端回送 65 字节自己的公钥;双方用 HKDF 派生 control/video/audio 三把 32 字节子密钥。
|
||
//! 3. 后续控制帧使用 `SecureControlChannel`(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。
|
||
//! 4. 视频/音频通过 UDP 41000/41002 发送,使用媒体 v2 AES-GCM、认证分片和防重放窗口。
|
||
|
||
use std::collections::VecDeque;
|
||
use std::io::{Read, Write};
|
||
use std::net::{TcpListener, TcpStream, UdpSocket};
|
||
use std::sync::mpsc::{sync_channel, SyncSender};
|
||
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
||
use std::sync::{Arc, Mutex, OnceLock};
|
||
use std::thread::{self, JoinHandle};
|
||
use std::time::{Duration, Instant};
|
||
|
||
use crate::control::events::{
|
||
AccessEvent, ClipboardEvent, ConfigEvent, FileEvent, KeyAction, KeyboardEvent, MirrorEvent,
|
||
MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_ACCESS, MSG_CLIPBOARD,
|
||
MSG_MIRROR,
|
||
};
|
||
use crate::control::{ControlEvent, ControlEventKind};
|
||
|
||
use crate::control::SecureControlChannel;
|
||
use crate::crypto::{derive_subkey, EphemeralKeyPair};
|
||
use crate::media::receiver::MediaReceiver;
|
||
use crate::session::relay::{self, RelayChannel, RelayMessage};
|
||
use crate::session::tls::PinnedTlsStream;
|
||
|
||
pub const DEFAULT_CONTROL_PORT: u16 = 41001;
|
||
pub const DEFAULT_VIDEO_PORT: u16 = 41000;
|
||
pub const DEFAULT_AUDIO_PORT: u16 = 41002;
|
||
const PUBLIC_KEY_LEN: usize = 65;
|
||
const MAX_FRAME: usize = 64 * 1024;
|
||
/// 中继轮询周期:信令 `/relay/poll` 立即返回,100ms 兼顾时延与请求量。
|
||
const RELAY_POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||
/// 中继请求超时(信令服务器不可达时尽快失败,避免拖住停止/重启)。
|
||
const RELAY_REQUEST_TIMEOUT: Duration = Duration::from_secs(2);
|
||
/// 中继握手窗口:被控端可能还没开始轮询,期间反复重发 `hs`。
|
||
const RELAY_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15);
|
||
|
||
#[derive(Debug, Clone, Default)]
|
||
pub struct DemoStatus {
|
||
pub running: bool,
|
||
/// 当前控制通道是否走信令中继(true 时画面无法直传)。
|
||
pub relay: bool,
|
||
pub peer_connected: bool,
|
||
pub key_established: bool,
|
||
pub peer_ip: String,
|
||
pub control_key_prefix: String,
|
||
pub video_key_prefix: String,
|
||
pub audio_key_prefix: String,
|
||
pub events: Vec<String>,
|
||
}
|
||
|
||
impl DemoStatus {
|
||
pub fn to_json(&self) -> String {
|
||
let events = self
|
||
.events
|
||
.iter()
|
||
.map(|event| format!("\"{}\"", event.replace('"', "\\\"")))
|
||
.collect::<Vec<_>>()
|
||
.join(",");
|
||
format!(
|
||
concat!(
|
||
"{{\"running\":{},\"relay\":{},\"peerConnected\":{},\"keyEstablished\":{},",
|
||
"\"peerIp\":\"{}\",\"controlKey\":\"{}\",\"videoKey\":\"{}\",",
|
||
"\"audioKey\":\"{}\",\"events\":[{}]}}"
|
||
),
|
||
self.running,
|
||
self.relay,
|
||
self.peer_connected,
|
||
self.key_established,
|
||
self.peer_ip.replace('"', ""),
|
||
self.control_key_prefix,
|
||
self.video_key_prefix,
|
||
self.audio_key_prefix,
|
||
events
|
||
)
|
||
}
|
||
}
|
||
|
||
/// 控制帧写端:直连写 TCP,跨网段写信令中继,启用 TLS 时写加密流。
|
||
#[derive(Clone)]
|
||
enum ControlSink {
|
||
Tcp(Arc<Mutex<TcpStream>>),
|
||
Relay(Arc<RelayChannel>),
|
||
Tls(Arc<Mutex<PinnedTlsStream>>),
|
||
}
|
||
|
||
impl ControlSink {
|
||
fn send(&self, frame: &[u8]) -> Result<(), String> {
|
||
match self {
|
||
Self::Tcp(stream) => {
|
||
let mut stream = stream.lock().map_err(|_| "控制写端锁不可用".to_string())?;
|
||
stream
|
||
.write_all(frame)
|
||
.and_then(|_| stream.flush())
|
||
.map_err(|error| format!("控制帧下发失败:{}", error))
|
||
}
|
||
Self::Relay(channel) => channel
|
||
.send_frame(frame)
|
||
.map_err(|error| format!("中继下发失败:{}", error)),
|
||
Self::Tls(stream) => {
|
||
let mut stream = stream.lock().map_err(|_| "控制写端锁不可用".to_string())?;
|
||
stream
|
||
.write_all(frame)
|
||
.map_err(|error| format!("控制帧下发失败:{}", error))
|
||
}
|
||
}
|
||
}
|
||
|
||
fn is_relay(&self) -> bool {
|
||
matches!(self, Self::Relay(_))
|
||
}
|
||
|
||
/// 只对 TCP/TLS 生效:打断阻塞中的读,让控制连接尽快退出。
|
||
fn shutdown(&self) {
|
||
match self {
|
||
Self::Tcp(stream) => {
|
||
if let Ok(stream) = stream.lock() {
|
||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||
}
|
||
}
|
||
Self::Tls(stream) => {
|
||
if let Ok(stream) = stream.lock() {
|
||
stream.shutdown();
|
||
}
|
||
}
|
||
Self::Relay(_) => {}
|
||
}
|
||
}
|
||
}
|
||
|
||
struct ControlSender {
|
||
sink: ControlSink,
|
||
outbound: SyncSender<ControlEvent>,
|
||
}
|
||
|
||
impl ControlSender {
|
||
fn new(sink: ControlSink, channel: Arc<SecureControlChannel>, shared: &Arc<Shared>) -> Self {
|
||
let (outbound, pending) = sync_channel::<ControlEvent>(128);
|
||
let writer = sink.clone();
|
||
let shared = Arc::downgrade(shared);
|
||
thread::spawn(move || {
|
||
while let Ok(event) = pending.recv() {
|
||
// Same channel as the reader/keepalive: never reset its nonce counter.
|
||
let result = channel.encode(&event)
|
||
.map_err(|error| error.to_string())
|
||
.and_then(|frame| writer.send(&frame));
|
||
if let Some(shared) = shared.upgrade() {
|
||
match &result {
|
||
Ok(()) => shared.push_event(format!("sent:seq={}:type={}", event.sequence(), event.msg_type())),
|
||
Err(error) => shared.push_event(format!("error:control-send:{}", error)),
|
||
}
|
||
}
|
||
if result.is_err() {
|
||
writer.shutdown();
|
||
break;
|
||
}
|
||
}
|
||
});
|
||
Self { sink, outbound }
|
||
}
|
||
}
|
||
|
||
/// 被控端上行的控制事件(mirror 应答 / 剪贴板),供 UI 侧轮询消费。
|
||
///
|
||
/// 与 `events`(诊断用的字符串环形缓冲)分开:这里只放界面真正要处理的事件,
|
||
/// 取走即出队,不会因为诊断日志刷太快把有用事件挤掉。
|
||
#[derive(Debug, Clone)]
|
||
struct InboundEvent {
|
||
msg_type: u8,
|
||
action: i32,
|
||
text: String,
|
||
}
|
||
|
||
impl InboundEvent {
|
||
fn to_json(&self) -> String {
|
||
format!(
|
||
"{{\"type\":{},\"action\":{},\"text\":\"{}\"}}",
|
||
self.msg_type,
|
||
self.action,
|
||
escape_json(&self.text)
|
||
)
|
||
}
|
||
}
|
||
|
||
fn escape_json(text: &str) -> String {
|
||
let mut out = String::with_capacity(text.len());
|
||
for ch in text.chars() {
|
||
match ch {
|
||
'"' => out.push_str("\\\""),
|
||
'\\' => out.push_str("\\\\"),
|
||
'\n' => out.push_str("\\n"),
|
||
'\r' => out.push_str("\\r"),
|
||
'\t' => out.push_str("\\t"),
|
||
control if (control as u32) < 0x20 => out.push(' '),
|
||
other => out.push(other),
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
struct Shared {
|
||
running: AtomicBool,
|
||
/// 中继会话线程是否在跑(与直连控制通道互斥使用 `sender`)。
|
||
relay_running: AtomicBool,
|
||
peer_connected: AtomicBool,
|
||
key_established: AtomicBool,
|
||
peer_ip: Mutex<String>,
|
||
control_key: Mutex<Option<[u8; 32]>>,
|
||
video_key: Mutex<Option<[u8; 32]>>,
|
||
audio_key: Mutex<Option<[u8; 32]>>,
|
||
video_receiver: Mutex<MediaReceiver>,
|
||
audio_receiver: Mutex<MediaReceiver>,
|
||
sender: Mutex<Option<ControlSender>>,
|
||
events: Mutex<Vec<String>>,
|
||
inbound: Mutex<VecDeque<InboundEvent>>,
|
||
/// 控制通道文件子协议(msgType=7)的响应队列,由请求方同步取走。
|
||
file_responses: Mutex<VecDeque<String>>,
|
||
}
|
||
|
||
impl Shared {
|
||
fn new() -> Self {
|
||
Self {
|
||
running: AtomicBool::new(false),
|
||
relay_running: AtomicBool::new(false),
|
||
peer_connected: AtomicBool::new(false),
|
||
key_established: AtomicBool::new(false),
|
||
peer_ip: Mutex::new(String::new()),
|
||
control_key: Mutex::new(None),
|
||
video_key: Mutex::new(None),
|
||
audio_key: Mutex::new(None),
|
||
video_receiver: Mutex::new(MediaReceiver::default()),
|
||
audio_receiver: Mutex::new(MediaReceiver::default()),
|
||
sender: Mutex::new(None),
|
||
events: Mutex::new(Vec::new()),
|
||
inbound: Mutex::new(VecDeque::new()),
|
||
file_responses: Mutex::new(VecDeque::new()),
|
||
}
|
||
}
|
||
|
||
fn push_event(&self, event: String) {
|
||
if let Ok(mut queue) = self.events.lock() {
|
||
if queue.len() >= 200 {
|
||
queue.remove(0);
|
||
}
|
||
queue.push(event);
|
||
}
|
||
}
|
||
|
||
fn push_inbound(&self, event: InboundEvent) {
|
||
if let Ok(mut queue) = self.inbound.lock() {
|
||
// 界面没及时消费时丢最旧的,避免无限增长。
|
||
if queue.len() >= 64 {
|
||
queue.pop_front();
|
||
}
|
||
queue.push_back(event);
|
||
}
|
||
}
|
||
|
||
fn clear_inbound(&self) {
|
||
if let Ok(mut queue) = self.inbound.lock() {
|
||
queue.clear();
|
||
}
|
||
}
|
||
|
||
fn push_file_response(&self, json: String) {
|
||
if let Ok(mut queue) = self.file_responses.lock() {
|
||
// 文件与投屏是两条独立链路;没人消费时最多留 16 条,避免无限增长。
|
||
if queue.len() >= 16 {
|
||
queue.pop_front();
|
||
}
|
||
queue.push_back(json);
|
||
}
|
||
}
|
||
|
||
fn take_file_response(&self, timeout: Duration) -> Option<String> {
|
||
let deadline = std::time::Instant::now() + timeout;
|
||
loop {
|
||
if let Ok(mut queue) = self.file_responses.lock() {
|
||
if let Some(json) = queue.pop_front() {
|
||
return Some(json);
|
||
}
|
||
}
|
||
if std::time::Instant::now() >= deadline {
|
||
return None;
|
||
}
|
||
thread::sleep(Duration::from_millis(20));
|
||
}
|
||
}
|
||
|
||
fn status(&self) -> DemoStatus {
|
||
let key_prefix = |key: &Mutex<Option<[u8; 32]>>| -> String {
|
||
key.lock()
|
||
.ok()
|
||
.and_then(|guard| *guard)
|
||
.map(|bytes| {
|
||
bytes[..4]
|
||
.iter()
|
||
.map(|byte| format!("{:02x}", byte))
|
||
.collect()
|
||
})
|
||
.unwrap_or_default()
|
||
};
|
||
DemoStatus {
|
||
running: self.running.load(Ordering::Relaxed),
|
||
relay: self.relay_running.load(Ordering::Relaxed),
|
||
peer_connected: self.peer_connected.load(Ordering::Relaxed),
|
||
key_established: self.key_established.load(Ordering::Relaxed),
|
||
peer_ip: self.peer_ip.lock().map(|value| value.clone()).unwrap_or_default(),
|
||
control_key_prefix: key_prefix(&self.control_key),
|
||
video_key_prefix: key_prefix(&self.video_key),
|
||
audio_key_prefix: key_prefix(&self.audio_key),
|
||
events: self.events.lock().map(|value| value.clone()).unwrap_or_default(),
|
||
}
|
||
}
|
||
}
|
||
|
||
struct ServerHandle {
|
||
shared: Arc<Shared>,
|
||
threads: Mutex<Vec<JoinHandle<()>>>,
|
||
/// 中继会话线程单独保存:中继与直连可以同时存在,不能一起 join。
|
||
relay_thread: Mutex<Option<JoinHandle<()>>>,
|
||
}
|
||
|
||
static SERVER: OnceLock<ServerHandle> = OnceLock::new();
|
||
|
||
/// 期望的对端 TLS 证书指纹;为空表示对端不支持 TLS(走明文,兼容旧版本)。
|
||
static EXPECTED_TLS: Mutex<String> = Mutex::new(String::new());
|
||
|
||
/// 设置本机作为 TLS 客户端时要求的证书指纹(`sha256:...`,空串表示禁用 TLS)。
|
||
pub fn set_tls_fingerprint(fingerprint: &str) {
|
||
if let Ok(mut guard) = EXPECTED_TLS.lock() {
|
||
*guard = fingerprint.trim().to_string();
|
||
}
|
||
}
|
||
|
||
fn expected_tls_fingerprint() -> String {
|
||
EXPECTED_TLS
|
||
.lock()
|
||
.map(|guard| guard.clone())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
fn server_handle() -> &'static ServerHandle {
|
||
SERVER.get_or_init(|| ServerHandle {
|
||
shared: Arc::new(Shared::new()),
|
||
threads: Mutex::new(Vec::new()),
|
||
relay_thread: Mutex::new(None),
|
||
})
|
||
}
|
||
|
||
/// 回收上一轮留下的监听线程。
|
||
///
|
||
/// `stop()` 只是置标志,线程退出有几十毫秒延迟;必须 join 掉才能保证监听端口
|
||
/// 真正释放,否则紧接着重新 `start` 会撞上 `Address already in use`,
|
||
/// 导致「断开后重连一直连不上」。
|
||
fn join_threads(handle: &ServerHandle) {
|
||
let threads = handle
|
||
.threads
|
||
.lock()
|
||
.map(|mut guard| std::mem::take(&mut *guard))
|
||
.unwrap_or_default();
|
||
for thread in threads {
|
||
let _ = thread.join();
|
||
}
|
||
}
|
||
|
||
/// 回收上一轮中继线程。轮询带 2s 超时,最坏情况下这里会等这么久。
|
||
fn join_relay_thread(handle: &ServerHandle) {
|
||
let thread = handle
|
||
.relay_thread
|
||
.lock()
|
||
.ok()
|
||
.and_then(|mut guard| guard.take());
|
||
if let Some(thread) = thread {
|
||
let _ = thread.join();
|
||
}
|
||
}
|
||
|
||
/// 关掉当前控制连接,让阻塞在 `read` 上的 `handle_peer` 立刻返回,
|
||
/// 从而尽快释放监听端口。
|
||
fn shutdown_control_channel(shared: &Shared) {
|
||
let sender = shared
|
||
.sender
|
||
.lock()
|
||
.ok()
|
||
.and_then(|mut guard| guard.take());
|
||
if let Some(sender) = sender {
|
||
sender.sink.shutdown();
|
||
}
|
||
}
|
||
|
||
/// 清掉上一次会话的密钥与控制写端,避免重连后误用旧密钥。
|
||
fn reset_session_state(shared: &Shared) {
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
*guard = None;
|
||
}
|
||
for slot in [&shared.control_key, &shared.video_key, &shared.audio_key] {
|
||
if let Ok(mut guard) = slot.lock() {
|
||
*guard = None;
|
||
}
|
||
}
|
||
shared.clear_inbound();
|
||
if let Ok(mut queue) = shared.file_responses.lock() {
|
||
queue.clear();
|
||
}
|
||
shared.peer_connected.store(false, Ordering::SeqCst);
|
||
shared.key_established.store(false, Ordering::SeqCst);
|
||
if let Ok(mut ip) = shared.peer_ip.lock() {
|
||
ip.clear();
|
||
}
|
||
}
|
||
|
||
/// 绑定端口时重试若干次:上一次的监听套接字可能刚关闭、内核尚未回收。
|
||
/// 只在「端口被占用」时重试,其它错误(权限、地址不可用)立刻返回。
|
||
fn retry_bind<T>(mut attempt_bind: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
|
||
let mut last_error = None;
|
||
for _ in 0..20 {
|
||
match attempt_bind() {
|
||
Ok(value) => return Ok(value),
|
||
Err(error) => {
|
||
if error.kind() != std::io::ErrorKind::AddrInUse {
|
||
return Err(error);
|
||
}
|
||
last_error = Some(error);
|
||
thread::sleep(Duration::from_millis(50));
|
||
}
|
||
}
|
||
}
|
||
Err(last_error.unwrap_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "绑定失败")))
|
||
}
|
||
|
||
/// 启动 demo 服务端。已运行或端口已就绪时返回 Ok(幂等)。
|
||
pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(), String> {
|
||
let handle = server_handle();
|
||
if handle.shared.running.load(Ordering::SeqCst) {
|
||
return Ok(());
|
||
}
|
||
// 上一轮的线程可能还没退干净,先 join 再重新绑定端口。
|
||
join_threads(handle);
|
||
reset_session_state(&handle.shared);
|
||
|
||
let result = (|| -> Result<(), String> {
|
||
let listener = retry_bind(|| TcpListener::bind(("0.0.0.0", control_port)))
|
||
.map_err(|error| format!("监听 TCP {} 失败:{}", control_port, error))?;
|
||
let video = retry_bind(|| UdpSocket::bind(("0.0.0.0", video_port)))
|
||
.map_err(|error| format!("监听 UDP {} 失败:{}", video_port, error))?;
|
||
let audio = retry_bind(|| UdpSocket::bind(("0.0.0.0", audio_port)))
|
||
.map_err(|error| format!("监听 UDP {} 失败:{}", audio_port, error))?;
|
||
// 一个关键帧可连续发送数百个小分片;默认接收缓冲过小会在解密前丢包。
|
||
// 系统可能钳制大小,设置失败只记录,不阻止会话建立。
|
||
for socket in [&video, &audio] {
|
||
if let Err(error) = socket2::SockRef::from(socket).set_recv_buffer_size(4 * 1024 * 1024) {
|
||
handle.shared.push_event(format!("warning:udp:receive-buffer:{}", error));
|
||
}
|
||
}
|
||
listener
|
||
.set_nonblocking(true)
|
||
.map_err(|error| format!("设置 TCP 非阻塞失败:{}", error))?;
|
||
video
|
||
.set_read_timeout(Some(Duration::from_millis(200)))
|
||
.map_err(|error| format!("设置 UDP 超时失败:{}", error))?;
|
||
audio
|
||
.set_read_timeout(Some(Duration::from_millis(200)))
|
||
.map_err(|error| format!("设置 UDP 超时失败:{}", error))?;
|
||
|
||
handle.shared.running.store(true, Ordering::SeqCst);
|
||
let shared = Arc::clone(&handle.shared);
|
||
let tcp = thread::spawn(move || run_tcp(listener, shared));
|
||
let video_thread = {
|
||
let shared = Arc::clone(&handle.shared);
|
||
thread::spawn(move || run_udp(video, shared, "video"))
|
||
};
|
||
let audio_thread = {
|
||
let shared = Arc::clone(&handle.shared);
|
||
thread::spawn(move || run_udp(audio, shared, "audio"))
|
||
};
|
||
if let Ok(mut threads) = handle.threads.lock() {
|
||
threads.extend([tcp, video_thread, audio_thread]);
|
||
}
|
||
Ok(())
|
||
})();
|
||
|
||
if result.is_err() {
|
||
handle.shared.running.store(false, Ordering::SeqCst);
|
||
join_threads(handle);
|
||
}
|
||
result
|
||
}
|
||
|
||
/// 停止 demo 服务端。链路与监听都会断开,可再次 [start]。
|
||
pub fn stop() {
|
||
let handle = server_handle();
|
||
handle.shared.running.store(false, Ordering::SeqCst);
|
||
handle.shared.relay_running.store(false, Ordering::SeqCst);
|
||
// 先断连接再 join,否则 handle_peer 要等到读超时才退出,端口释放被拖慢。
|
||
shutdown_control_channel(&handle.shared);
|
||
join_relay_thread(handle);
|
||
join_threads(handle);
|
||
reset_session_state(&handle.shared);
|
||
if let Ok(mut events) = handle.shared.events.lock() {
|
||
events.clear();
|
||
}
|
||
crate::media::stream::clear();
|
||
crate::media::audio::clear();
|
||
}
|
||
|
||
/// 读取当前状态快照。
|
||
pub fn status() -> DemoStatus {
|
||
server_handle().shared.status()
|
||
}
|
||
|
||
/// 通过信令服务器建立中继控制会话(跨网段、无端口映射时使用)。
|
||
///
|
||
/// 中继同时承载控制帧与加密媒体分片(`kind=frame` / `kind=media`),可跨网段投屏。
|
||
/// 幂等:重复调用会先停掉上一轮中继,再按新参数重连。
|
||
pub fn start_relay(base_url: &str, peer_id: &str) -> Result<(), String> {
|
||
let base_url = base_url.trim();
|
||
let peer_id = peer_id.trim();
|
||
if base_url.is_empty() {
|
||
return Err("中继需要信令服务器地址".to_string());
|
||
}
|
||
if peer_id.is_empty() {
|
||
return Err("中继需要被控端设备 id".to_string());
|
||
}
|
||
let handle = server_handle();
|
||
handle.shared.relay_running.store(false, Ordering::SeqCst);
|
||
join_relay_thread(handle);
|
||
if handle.shared.key_established.load(Ordering::SeqCst)
|
||
|| handle.shared.peer_connected.load(Ordering::SeqCst)
|
||
{
|
||
return Err("已有直连会话,请先断开再切换到中继".to_string());
|
||
}
|
||
// 地址不合法(例如当前还不支持 https://)时立刻回错,别让界面等到握手超时。
|
||
RelayChannel::new(base_url, "relay-probe", peer_id, RELAY_REQUEST_TIMEOUT)
|
||
.map_err(|error| error.to_string())?;
|
||
reset_session_state(&handle.shared);
|
||
handle.shared.relay_running.store(true, Ordering::SeqCst);
|
||
let shared = Arc::clone(&handle.shared);
|
||
let base_url = base_url.to_string();
|
||
let peer_id = peer_id.to_string();
|
||
let thread = thread::spawn(move || run_relay(shared, base_url, peer_id));
|
||
if let Ok(mut slot) = handle.relay_thread.lock() {
|
||
*slot = Some(thread);
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// 停止中继会话(直连控制通道不受影响)。
|
||
pub fn stop_relay() {
|
||
let handle = server_handle();
|
||
handle.shared.relay_running.store(false, Ordering::SeqCst);
|
||
join_relay_thread(handle);
|
||
}
|
||
|
||
fn relay_alive(shared: &Shared) -> bool {
|
||
// 中继不依赖本机 demo 监听,只看自身的运行标志。
|
||
shared.relay_running.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// 会话结束的收尾:通知对端、清掉中继写端与密钥。
|
||
fn finish_relay(shared: &Shared, channel: &RelayChannel) {
|
||
let _ = channel.send_bye();
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
if guard
|
||
.as_ref()
|
||
.map(|sender| sender.sink.is_relay())
|
||
.unwrap_or(false)
|
||
{
|
||
*guard = None;
|
||
}
|
||
}
|
||
shared.peer_connected.store(false, Ordering::Relaxed);
|
||
shared.key_established.store(false, Ordering::Relaxed);
|
||
for slot in [&shared.control_key, &shared.video_key, &shared.audio_key] {
|
||
if let Ok(mut guard) = slot.lock() {
|
||
*guard = None;
|
||
}
|
||
}
|
||
shared.relay_running.store(false, Ordering::SeqCst);
|
||
}
|
||
|
||
/// 中继会话:先做 ECDH 握手,再把控制帧收发挂到 `/relay` 上。
|
||
fn run_relay(shared: Arc<Shared>, base_url: String, peer_id: String) {
|
||
let self_id = relay::local_id();
|
||
let channel = match RelayChannel::new(&base_url, &self_id, &peer_id, RELAY_REQUEST_TIMEOUT) {
|
||
Ok(channel) => channel,
|
||
Err(error) => {
|
||
shared.push_event(format!("error:relay:{}", error));
|
||
shared.relay_running.store(false, Ordering::SeqCst);
|
||
return;
|
||
}
|
||
};
|
||
let pair = match EphemeralKeyPair::generate() {
|
||
Ok(pair) => pair,
|
||
Err(_) => {
|
||
shared.push_event("error:relay:ecdh-generate".to_string());
|
||
shared.relay_running.store(false, Ordering::SeqCst);
|
||
return;
|
||
}
|
||
};
|
||
let local_public = pair.public_bytes().to_vec();
|
||
shared.push_event(format!("relay:connecting:{}", peer_id));
|
||
|
||
// 被控端可能还没开始轮询,每轮重发一次 `hs`,收到 `hsAck` 即进入会话。
|
||
let mut peer_public: Option<Vec<u8>> = None;
|
||
let mut peer_left = false;
|
||
let deadline = Instant::now() + RELAY_HANDSHAKE_TIMEOUT;
|
||
while relay_alive(&shared) && Instant::now() < deadline {
|
||
if let Err(error) = channel.send(&RelayMessage::Hello {
|
||
from: self_id.clone(),
|
||
public_key: local_public.clone(),
|
||
}) {
|
||
shared.push_event(format!("error:relay:hello:{}", error));
|
||
}
|
||
let until = Instant::now() + Duration::from_secs(1);
|
||
while relay_alive(&shared) && Instant::now() < until {
|
||
match channel.poll() {
|
||
Ok(messages) => {
|
||
for message in messages {
|
||
match message {
|
||
RelayMessage::HelloAck { public_key, .. } => {
|
||
peer_public = Some(public_key);
|
||
}
|
||
RelayMessage::Bye { .. } => peer_left = true,
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
Err(error) => shared.push_event(format!("error:relay:poll:{}", error)),
|
||
}
|
||
if peer_public.is_some() || peer_left {
|
||
break;
|
||
}
|
||
thread::sleep(RELAY_POLL_INTERVAL);
|
||
}
|
||
if peer_public.is_some() || peer_left {
|
||
break;
|
||
}
|
||
}
|
||
|
||
let Some(peer_public) = peer_public else {
|
||
if relay_alive(&shared) && !peer_left {
|
||
shared.push_event("error:relay:handshake-timeout".to_string());
|
||
}
|
||
finish_relay(&shared, &channel);
|
||
return;
|
||
};
|
||
|
||
let shared_secret = match pair.into_shared_secret(&peer_public) {
|
||
Ok(secret) => secret,
|
||
Err(_) => {
|
||
shared.push_event("error:relay:ecdh-agree".to_string());
|
||
finish_relay(&shared, &channel);
|
||
return;
|
||
}
|
||
};
|
||
let control = match derive_subkey(&shared_secret, b"lancast/control/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => {
|
||
finish_relay(&shared, &channel);
|
||
return;
|
||
}
|
||
};
|
||
let video = match derive_subkey(&shared_secret, b"lancast/video/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => {
|
||
finish_relay(&shared, &channel);
|
||
return;
|
||
}
|
||
};
|
||
let audio = match derive_subkey(&shared_secret, b"lancast/audio/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => {
|
||
finish_relay(&shared, &channel);
|
||
return;
|
||
}
|
||
};
|
||
for (slot, key) in [
|
||
(&shared.control_key, control),
|
||
(&shared.video_key, video),
|
||
(&shared.audio_key, audio),
|
||
] {
|
||
if let Ok(mut guard) = slot.lock() {
|
||
*guard = Some(key);
|
||
}
|
||
}
|
||
shared.key_established.store(true, Ordering::SeqCst);
|
||
shared.peer_connected.store(true, Ordering::SeqCst);
|
||
if let Ok(mut ip) = shared.peer_ip.lock() {
|
||
*ip = format!("relay:{}", peer_id);
|
||
}
|
||
shared.push_event("relay:key-established".to_string());
|
||
|
||
let sink = ControlSink::Relay(Arc::new(channel.clone()));
|
||
let control_channel = Arc::new(SecureControlChannel::new(control));
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
*guard = Some(ControlSender::new(sink.clone(), Arc::clone(&control_channel), &shared));
|
||
}
|
||
|
||
let mut buffer: Vec<u8> = Vec::new();
|
||
// 中继模式下媒体也走 TCP,分片复用与 UDP 相同的重组器,保证解码路径一致。
|
||
let mut video_reassembler = crate::media::stream::Reassembler::new();
|
||
let mut audio_reassembler = crate::media::stream::Reassembler::new();
|
||
let mut ping_sequence = 0u16;
|
||
let mut last_ping = Instant::now();
|
||
let mut poll_errors = 0u32;
|
||
while relay_alive(&shared) && !peer_left {
|
||
match channel.poll() {
|
||
Ok(messages) => {
|
||
poll_errors = 0;
|
||
for message in messages {
|
||
match message {
|
||
RelayMessage::Frame { data, .. } => {
|
||
buffer.extend_from_slice(&data);
|
||
if buffer.len() > MAX_FRAME {
|
||
shared.push_event("error:relay:frame-too-large".to_string());
|
||
buffer.clear();
|
||
continue;
|
||
}
|
||
loop {
|
||
match control_channel.decode(&buffer) {
|
||
Ok(Some((event, consumed))) => {
|
||
buffer.drain(..consumed);
|
||
dispatch_control_event(
|
||
&shared,
|
||
&event,
|
||
&control_channel,
|
||
&sink,
|
||
);
|
||
}
|
||
Ok(None) => break,
|
||
Err(error) => {
|
||
shared.push_event(format!("error:relay:control:{}", error));
|
||
buffer.clear();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
RelayMessage::Media { video, audio, .. } => {
|
||
ingest_relay_media(
|
||
&shared,
|
||
"video",
|
||
&video,
|
||
&mut video_reassembler,
|
||
&peer_id,
|
||
);
|
||
ingest_relay_media(
|
||
&shared,
|
||
"audio",
|
||
&audio,
|
||
&mut audio_reassembler,
|
||
&peer_id,
|
||
);
|
||
}
|
||
RelayMessage::Bye { .. } => peer_left = true,
|
||
RelayMessage::Hello { .. } | RelayMessage::HelloAck { .. } => {}
|
||
}
|
||
}
|
||
}
|
||
Err(error) => {
|
||
poll_errors += 1;
|
||
if poll_errors == 1 || poll_errors % 20 == 0 {
|
||
shared.push_event(format!("error:relay:poll:{}", error));
|
||
}
|
||
// 连续约 10 秒打不通信令服务器,结束会话交给上层重连。
|
||
if poll_errors >= 100 {
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if peer_left || !relay_alive(&shared) {
|
||
break;
|
||
}
|
||
if last_ping.elapsed() >= Duration::from_secs(2) {
|
||
ping_sequence = ping_sequence.wrapping_add(1);
|
||
let ping = ControlEvent::new(ping_sequence, ControlEventKind::Ping(0));
|
||
if let Ok(frame) = control_channel.encode(&ping) {
|
||
let _ = sink.send(&frame);
|
||
}
|
||
last_ping = Instant::now();
|
||
}
|
||
thread::sleep(RELAY_POLL_INTERVAL);
|
||
}
|
||
shared.push_event("relay:closed".to_string());
|
||
finish_relay(&shared, &channel);
|
||
}
|
||
|
||
/// 解密一批中继媒体分片并逐片喂给消费函数;坏包只丢该片,不影响其它分片。
|
||
fn ingest_relay_media(
|
||
shared: &Shared,
|
||
kind: &str,
|
||
packets: &[Vec<u8>],
|
||
reassembler: &mut crate::media::stream::Reassembler,
|
||
peer_id: &str,
|
||
) {
|
||
if packets.is_empty() {
|
||
return;
|
||
}
|
||
let key_slot = if kind == "video" {
|
||
&shared.video_key
|
||
} else {
|
||
&shared.audio_key
|
||
};
|
||
let key = match key_slot.lock().ok().and_then(|guard| *guard) {
|
||
Some(key) => key,
|
||
None => return,
|
||
};
|
||
for packet in packets {
|
||
match decrypt_relay_media(&key, packet) {
|
||
Some(plain) => {
|
||
consume_media_packet(shared, kind, reassembler, &plain, &format!("relay:{}", peer_id))
|
||
}
|
||
None => shared.push_event(format!("error:relay:media-{}:decrypt", kind)),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 查看队首的上行事件(mirror 应答 / 剪贴板)JSON,队列空时返回 None。
|
||
///
|
||
/// 与 [`pop_inbound_event`] 配对使用:调用方先把 JSON 拷进自己的缓冲,再出队,
|
||
/// 避免缓冲不够时把事件丢掉。
|
||
pub fn peek_inbound_event() -> Option<String> {
|
||
let shared = &server_handle().shared;
|
||
let queue = shared.inbound.lock().ok()?;
|
||
queue.front().map(|event| event.to_json())
|
||
}
|
||
|
||
/// 丢弃队首的上行事件(通常紧跟在 [`peek_inbound_event`] 之后)。
|
||
pub fn pop_inbound_event() {
|
||
let shared = &server_handle().shared;
|
||
if let Ok(mut queue) = shared.inbound.lock() {
|
||
queue.pop_front();
|
||
}
|
||
}
|
||
|
||
/// 发送一条文件子协议请求(msgType=7)并等待响应。
|
||
///
|
||
/// 子协议是一问一答的:用互斥锁串行化在途请求,并在发送前清掉上一轮超时残留的响应,
|
||
/// 否则可能把上一个请求的 `chunkAck` 当成这一次的结果。
|
||
pub fn request_file(json: String, timeout: Duration) -> Result<String, String> {
|
||
static FILE_LOCK: Mutex<()> = Mutex::new(());
|
||
static FILE_SEQUENCE: AtomicU16 = AtomicU16::new(1);
|
||
let _guard = FILE_LOCK
|
||
.lock()
|
||
.map_err(|_| "文件请求锁不可用".to_string())?;
|
||
if let Ok(mut queue) = server_handle().shared.file_responses.lock() {
|
||
queue.clear();
|
||
}
|
||
let sequence = FILE_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||
send_control(file_event(sequence, json))?;
|
||
server_handle()
|
||
.shared
|
||
.take_file_response(timeout)
|
||
.ok_or_else(|| "等待被控端文件服务响应超时".to_string())
|
||
}
|
||
|
||
/// 把控制事件编码为 AES-GCM 帧并下发给当前被控端。
|
||
/// Ok 表示进入有界发送队列;实际网络写入在后台顺序执行,错误记录到状态事件。
|
||
pub fn send_control(event: ControlEvent) -> Result<(), String> {
|
||
let handle = server_handle();
|
||
let sender = handle
|
||
.shared
|
||
.sender
|
||
.lock()
|
||
.map_err(|_| "控制通道锁不可用".to_string())?;
|
||
let sender = sender.as_ref().ok_or_else(|| "没有已连接的被控端".to_string())?;
|
||
sender.outbound.try_send(event).map_err(|error| format!("控制发送队列不可用:{}", error))
|
||
}
|
||
|
||
/// 构造触摸控制事件。
|
||
pub fn touch_event(sequence: u16, action: u8, pointer_id: u8, x: i16, y: i16, pressure: u16) -> Option<ControlEvent> {
|
||
Some(ControlEvent::new(sequence, ControlEventKind::Touch(TouchEvent {
|
||
action: TouchAction::from_u8(action)?,
|
||
pointer_id,
|
||
x,
|
||
y,
|
||
pressure,
|
||
})))
|
||
}
|
||
|
||
/// 构造按键控制事件。
|
||
pub fn key_event(sequence: u16, action: u8, keycode: u16, modifiers: u16) -> Option<ControlEvent> {
|
||
Some(ControlEvent::new(sequence, ControlEventKind::Key(KeyboardEvent {
|
||
action: KeyAction::from_u8(action)?,
|
||
keycode,
|
||
modifiers,
|
||
})))
|
||
}
|
||
|
||
/// 构造鼠标控制事件。
|
||
pub fn mouse_event(sequence: u16, action: u8, x: i16, y: i16, buttons: u8) -> Option<ControlEvent> {
|
||
Some(ControlEvent::new(sequence, ControlEventKind::Mouse(MouseEvent {
|
||
action: MouseAction::from_u8(action)?,
|
||
x,
|
||
y,
|
||
buttons,
|
||
})))
|
||
}
|
||
|
||
/// 构造滚轮控制事件。
|
||
pub fn wheel_event(sequence: u16, delta_x: i16, delta_y: i16, buttons: u8) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Wheel(WheelEvent { delta_x, delta_y, buttons }))
|
||
}
|
||
|
||
/// 构造剪贴板控制事件。
|
||
pub fn clipboard_event(sequence: u16, text: String) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Clipboard(ClipboardEvent { text }))
|
||
}
|
||
|
||
/// 构造 Ping 控制事件。
|
||
pub fn ping_event(sequence: u16, timestamp: u64) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Ping(timestamp))
|
||
}
|
||
|
||
/// 构造投屏请求/停止事件(主控端 → 被控端)。
|
||
/// 构造文件子协议事件(msgType=7)。
|
||
pub fn file_event(sequence: u16, json: String) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::File(FileEvent { json }))
|
||
}
|
||
|
||
pub fn mirror_event(sequence: u16, action: u8, message: String) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Mirror(MirrorEvent { action, message }))
|
||
}
|
||
|
||
/// msgType=9 会话配置帧:payload 是主控端拼好的 UTF-8 JSON。
|
||
pub fn config_event(sequence: u16, json: String) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Config(ConfigEvent { json }))
|
||
}
|
||
|
||
/// msgType=10 权限等级应答:payload 是被控端算出的有效等级 JSON。
|
||
pub fn access_event(sequence: u16, json: String) -> ControlEvent {
|
||
ControlEvent::new(sequence, ControlEventKind::Access(AccessEvent { json }))
|
||
}
|
||
|
||
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||
while shared.running.load(Ordering::Relaxed) {
|
||
match listener.accept() {
|
||
Ok((stream, address)) => {
|
||
// 中继会话期间拒绝新的直连:两套密钥同时存在只会互相覆盖。
|
||
if shared.relay_running.load(Ordering::SeqCst) {
|
||
shared.push_event(format!("peer-rejected:relay:{}", address));
|
||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||
continue;
|
||
}
|
||
// listener 是非阻塞的,accept 出的连接会继承该标志;改回阻塞以便 read_exact。
|
||
let _ = stream.set_nonblocking(false);
|
||
let _ = stream.set_nodelay(true);
|
||
let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
|
||
if let Ok(mut ip) = shared.peer_ip.lock() {
|
||
*ip = address.ip().to_string();
|
||
}
|
||
shared.peer_connected.store(true, Ordering::Relaxed);
|
||
shared.push_event(format!("peer:{}", address));
|
||
// 握手前给短一点的超时:半开连接不能长时间拖住监听线程(会推迟端口释放)。
|
||
let _ = stream.set_read_timeout(Some(Duration::from_millis(1200)));
|
||
handle_peer(stream, &shared);
|
||
shared.peer_connected.store(false, Ordering::Relaxed);
|
||
shared.key_established.store(false, Ordering::Relaxed);
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
*guard = None;
|
||
}
|
||
}
|
||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||
thread::sleep(Duration::from_millis(50));
|
||
}
|
||
Err(error) => {
|
||
// 监听套接字已坏:置回 not running,避免界面显示「已监听」却收不到连接。
|
||
shared.push_event(format!("error:listener:{}", error));
|
||
shared.running.store(false, Ordering::SeqCst);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn handle_peer(stream: TcpStream, shared: &Arc<Shared>) {
|
||
let fingerprint = expected_tls_fingerprint();
|
||
if fingerprint.is_empty() {
|
||
let mut stream = stream;
|
||
handle_peer_plain(&mut stream, shared);
|
||
return;
|
||
}
|
||
// 被控端先反连本机,但 TLS 角色是本机做客户端、被控端做服务端:
|
||
// 由本机发 ClientHello,并用发现信息里的 `tls` 指纹校验对端证书。
|
||
match PinnedTlsStream::accept(stream, &fingerprint) {
|
||
Ok(tls) => {
|
||
shared.push_event("tls:handshake-ok".to_string());
|
||
handle_peer_tls(Arc::new(Mutex::new(tls)), shared);
|
||
}
|
||
Err(error) => shared.push_event(format!("error:tls:{}", error)),
|
||
}
|
||
}
|
||
|
||
fn handle_peer_plain(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||
let local_pair = match EphemeralKeyPair::generate() {
|
||
Ok(pair) => pair,
|
||
Err(_) => {
|
||
shared.push_event("error:ecdh-generate".to_string());
|
||
return;
|
||
}
|
||
};
|
||
let local_public = local_pair.public_bytes().to_vec();
|
||
let mut peer_public = [0u8; PUBLIC_KEY_LEN];
|
||
if stream.read_exact(&mut peer_public).is_err() {
|
||
shared.push_event("error:peer-public".to_string());
|
||
return;
|
||
}
|
||
let shared_secret = match local_pair.into_shared_secret(&peer_public) {
|
||
Ok(secret) => secret,
|
||
Err(_) => {
|
||
shared.push_event("error:ecdh-agree".to_string());
|
||
return;
|
||
}
|
||
};
|
||
let control = match derive_subkey(&shared_secret, b"lancast/control/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => return,
|
||
};
|
||
let video = match derive_subkey(&shared_secret, b"lancast/video/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => return,
|
||
};
|
||
let audio = match derive_subkey(&shared_secret, b"lancast/audio/v1") {
|
||
Ok(key) => key,
|
||
Err(_) => return,
|
||
};
|
||
for (slot, key) in [(&shared.control_key, control), (&shared.video_key, video), (&shared.audio_key, audio)] {
|
||
if let Ok(mut guard) = slot.lock() {
|
||
*guard = Some(key);
|
||
}
|
||
}
|
||
shared.key_established.store(true, Ordering::Relaxed);
|
||
shared.push_event("key-established".to_string());
|
||
|
||
if stream.write_all(&local_public).is_err() {
|
||
return;
|
||
}
|
||
let _ = stream.flush();
|
||
// 握手完成,恢复正常读超时(兼作心跳周期)。
|
||
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
|
||
|
||
// 编解码共用一个实例:encode 走原子计数器,decode 只用报文里的 nonce。
|
||
let channel = Arc::new(SecureControlChannel::new(control));
|
||
let Ok(write_stream) = stream.try_clone() else {
|
||
shared.push_event("error:control-write-clone".to_string());
|
||
return;
|
||
};
|
||
let sink = ControlSink::Tcp(Arc::new(Mutex::new(write_stream)));
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
*guard = Some(ControlSender::new(sink.clone(), Arc::clone(&channel), shared));
|
||
}
|
||
let mut buffer = Vec::new();
|
||
let mut chunk = [0u8; 4096];
|
||
let mut keepalive_sequence = 0u16;
|
||
while shared.running.load(Ordering::Relaxed) {
|
||
let read = match stream.read(&mut chunk) {
|
||
Ok(0) => {
|
||
shared.push_event("control:eof".to_string());
|
||
break;
|
||
}
|
||
Ok(size) => size,
|
||
Err(error)
|
||
if matches!(
|
||
error.kind(),
|
||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||
) =>
|
||
{
|
||
keepalive_sequence = keepalive_sequence.wrapping_add(1);
|
||
let ping = ControlEvent::new(
|
||
keepalive_sequence,
|
||
ControlEventKind::Ping(0),
|
||
);
|
||
let Ok(frame) = channel.encode(&ping) else {
|
||
continue;
|
||
};
|
||
if sink.send(&frame).is_err() {
|
||
shared.push_event("control:keepalive-write-error".to_string());
|
||
break;
|
||
}
|
||
continue;
|
||
}
|
||
Err(error) => {
|
||
shared.push_event(format!("control:read-error:{}", error));
|
||
break;
|
||
}
|
||
};
|
||
buffer.extend_from_slice(&chunk[..read]);
|
||
if buffer.len() > MAX_FRAME {
|
||
shared.push_event("error:frame-too-large".to_string());
|
||
break;
|
||
}
|
||
loop {
|
||
match channel.decode(&buffer) {
|
||
Ok(Some((event, consumed))) => {
|
||
buffer.drain(..consumed);
|
||
dispatch_control_event(shared, &event, &channel, &sink);
|
||
}
|
||
Ok(None) => break,
|
||
Err(error) => {
|
||
shared.push_event(format!("error:control:{}", error));
|
||
buffer.clear();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 处理一帧已解出的控制事件:把界面要处理的事件入队,并回 `pong`。
|
||
/// 派生并安装 control/video/audio 三把子密钥,返回 control key。
|
||
fn install_session_keys(shared: &Shared, shared_secret: &[u8]) -> Option<[u8; 32]> {
|
||
let control = derive_subkey(shared_secret, b"lancast/control/v1").ok()?;
|
||
let video = derive_subkey(shared_secret, b"lancast/video/v1").ok()?;
|
||
let audio = derive_subkey(shared_secret, b"lancast/audio/v1").ok()?;
|
||
for (slot, key) in [
|
||
(&shared.control_key, control),
|
||
(&shared.video_key, video),
|
||
(&shared.audio_key, audio),
|
||
] {
|
||
if let Ok(mut guard) = slot.lock() {
|
||
*guard = Some(key);
|
||
}
|
||
}
|
||
shared.key_established.store(true, Ordering::Relaxed);
|
||
shared.push_event("key-established".to_string());
|
||
Some(control)
|
||
}
|
||
|
||
/// 在 TLS 流上读满指定长度;超时按整体 deadline 计算。
|
||
fn tls_read_exact(
|
||
tls: &Arc<Mutex<PinnedTlsStream>>,
|
||
buffer: &mut [u8],
|
||
timeout: Duration,
|
||
) -> bool {
|
||
let deadline = Instant::now() + timeout;
|
||
let mut filled = 0;
|
||
while filled < buffer.len() {
|
||
let result = {
|
||
let Ok(mut guard) = tls.lock() else {
|
||
return false;
|
||
};
|
||
guard.read(&mut buffer[filled..])
|
||
};
|
||
match result {
|
||
Ok(0) => return false,
|
||
Ok(size) => filled += size,
|
||
Err(error) if matches!(
|
||
error.kind(),
|
||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||
) =>
|
||
{
|
||
if Instant::now() >= deadline {
|
||
return false;
|
||
}
|
||
}
|
||
Err(_) => return false,
|
||
}
|
||
}
|
||
true
|
||
}
|
||
|
||
/// TLS 控制连接:与明文路径逻辑一致,只是读写都在加密流上,且读超时更短以便发心跳。
|
||
fn handle_peer_tls(tls: Arc<Mutex<PinnedTlsStream>>, shared: &Arc<Shared>) {
|
||
let local_pair = match EphemeralKeyPair::generate() {
|
||
Ok(pair) => pair,
|
||
Err(_) => {
|
||
shared.push_event("error:ecdh-generate".to_string());
|
||
return;
|
||
}
|
||
};
|
||
let local_public = local_pair.public_bytes().to_vec();
|
||
let mut peer_public = [0u8; PUBLIC_KEY_LEN];
|
||
if !tls_read_exact(&tls, &mut peer_public, Duration::from_secs(5)) {
|
||
shared.push_event("error:peer-public".to_string());
|
||
return;
|
||
}
|
||
let shared_secret = match local_pair.into_shared_secret(&peer_public) {
|
||
Ok(secret) => secret,
|
||
Err(_) => {
|
||
shared.push_event("error:ecdh-agree".to_string());
|
||
return;
|
||
}
|
||
};
|
||
let Some(control) = install_session_keys(shared, &shared_secret) else {
|
||
return;
|
||
};
|
||
if let Ok(mut stream) = tls.lock() {
|
||
if stream.write_all(&local_public).is_err() {
|
||
return;
|
||
}
|
||
}
|
||
// 握手完成,改短读超时:空闲时定期发 ping,同时不阻塞其它线程写入。
|
||
if let Ok(stream) = tls.lock() {
|
||
let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
|
||
}
|
||
|
||
let channel = Arc::new(SecureControlChannel::new(control));
|
||
let sink = ControlSink::Tls(Arc::clone(&tls));
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
*guard = Some(ControlSender::new(sink.clone(), Arc::clone(&channel), shared));
|
||
}
|
||
|
||
let socket = match tls.lock().ok().and_then(|stream| stream.socket_clone().ok()) {
|
||
Some(socket) => socket,
|
||
None => return,
|
||
};
|
||
let mut buffer = Vec::new();
|
||
let mut chunk = [0u8; 4096];
|
||
let mut keepalive_sequence = 0u16;
|
||
let mut last_ping = Instant::now();
|
||
while shared.running.load(Ordering::Relaxed) {
|
||
let read = {
|
||
let Ok(mut guard) = tls.lock() else {
|
||
break;
|
||
};
|
||
guard.read_buffered(&mut chunk)
|
||
};
|
||
// Wait for network readiness outside the TLS mutex, so a quiet peer
|
||
// cannot starve the input writer by immediately reacquiring the lock.
|
||
let read = match read {
|
||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||
match socket.peek(&mut [0u8; 1]) {
|
||
Ok(0) => Ok(0),
|
||
Ok(_) => match tls.lock() {
|
||
Ok(mut guard) => guard.read(&mut chunk),
|
||
Err(_) => break,
|
||
},
|
||
Err(error) => Err(error),
|
||
}
|
||
}
|
||
result => result,
|
||
};
|
||
match read {
|
||
Ok(0) => {
|
||
shared.push_event("control:eof".to_string());
|
||
break;
|
||
}
|
||
Ok(size) => {
|
||
buffer.extend_from_slice(&chunk[..size]);
|
||
if buffer.len() > MAX_FRAME {
|
||
shared.push_event("error:frame-too-large".to_string());
|
||
break;
|
||
}
|
||
loop {
|
||
match channel.decode(&buffer) {
|
||
Ok(Some((event, consumed))) => {
|
||
buffer.drain(..consumed);
|
||
dispatch_control_event(shared, &event, &channel, &sink);
|
||
}
|
||
Ok(None) => break,
|
||
Err(error) => {
|
||
shared.push_event(format!("error:control:{}", error));
|
||
buffer.clear();
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Err(error)
|
||
if matches!(
|
||
error.kind(),
|
||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||
) =>
|
||
{
|
||
if last_ping.elapsed() < Duration::from_secs(2) {
|
||
continue;
|
||
}
|
||
keepalive_sequence = keepalive_sequence.wrapping_add(1);
|
||
let ping = ControlEvent::new(keepalive_sequence, ControlEventKind::Ping(0));
|
||
if let Ok(frame) = channel.encode(&ping) {
|
||
if sink.send(&frame).is_err() {
|
||
shared.push_event("control:keepalive-write-error".to_string());
|
||
break;
|
||
}
|
||
}
|
||
last_ping = Instant::now();
|
||
}
|
||
Err(error) => {
|
||
shared.push_event(format!("control:read-error:{}", error));
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if let Ok(mut guard) = shared.sender.lock() {
|
||
let is_tls = guard
|
||
.as_ref()
|
||
.map(|sender| matches!(&sender.sink, ControlSink::Tls(_)))
|
||
.unwrap_or(false);
|
||
if is_tls {
|
||
*guard = None;
|
||
}
|
||
}
|
||
}
|
||
|
||
fn dispatch_control_event(
|
||
shared: &Shared,
|
||
event: &ControlEvent,
|
||
channel: &SecureControlChannel,
|
||
sink: &ControlSink,
|
||
) {
|
||
shared.push_event(format!(
|
||
"control:seq={}:type={}",
|
||
event.sequence(),
|
||
event.msg_type()
|
||
));
|
||
// 界面要处理的事件单独入队:诊断日志刷得快,不能只靠 events 环。
|
||
match &event.kind {
|
||
ControlEventKind::Mirror(mirror) => {
|
||
shared.push_inbound(InboundEvent {
|
||
msg_type: MSG_MIRROR,
|
||
action: i32::from(mirror.action),
|
||
text: mirror.message.clone(),
|
||
});
|
||
}
|
||
ControlEventKind::Access(access) => {
|
||
shared.push_inbound(InboundEvent {
|
||
msg_type: MSG_ACCESS,
|
||
action: 0,
|
||
text: access.json.clone(),
|
||
});
|
||
}
|
||
ControlEventKind::Clipboard(clipboard) => {
|
||
shared.push_inbound(InboundEvent {
|
||
msg_type: MSG_CLIPBOARD,
|
||
action: 0,
|
||
text: clipboard.text.clone(),
|
||
});
|
||
}
|
||
ControlEventKind::File(file) => {
|
||
// 文件响应可能很大(list 目录),走独立队列,不挤占界面事件。
|
||
shared.push_file_response(file.json.clone());
|
||
}
|
||
_ => {}
|
||
}
|
||
if let ControlEventKind::Ping(timestamp) = &event.kind {
|
||
let pong = ControlEvent::new(event.sequence(), ControlEventKind::Pong(*timestamp));
|
||
if let Ok(frame) = channel.encode(&pong) {
|
||
let _ = sink.send(&frame);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn run_udp(socket: UdpSocket, shared: Arc<Shared>, kind: &str) {
|
||
let mut buffer = [0u8; MAX_FRAME];
|
||
// 视频大帧会被发送端切成多个 UDP 分片,这里按序重组。
|
||
let mut reassembler = crate::media::stream::Reassembler::new();
|
||
while shared.running.load(Ordering::Relaxed) {
|
||
let (size, source) = match socket.recv_from(&mut buffer) {
|
||
Ok(value) => value,
|
||
Err(_) => continue,
|
||
};
|
||
consume_media_packet(&shared, kind, &mut reassembler, &buffer[..size], &source.to_string());
|
||
}
|
||
}
|
||
|
||
/// 校验并消费一个媒体分片(直连 UDP 与中继 `media` 消息共用)。
|
||
///
|
||
/// 视频访问单元重组后进入解码队列,由桌面端原生解码线程消费;音频目前只记录统计。
|
||
fn consume_media_packet(
|
||
shared: &Shared,
|
||
kind: &str,
|
||
reassembler: &mut crate::media::stream::Reassembler,
|
||
data: &[u8],
|
||
source: &str,
|
||
) {
|
||
let key_slot = if kind == "video" {
|
||
&shared.video_key
|
||
} else {
|
||
&shared.audio_key
|
||
};
|
||
let key_guard = match key_slot.lock() { Ok(guard) => guard, Err(_) => return };
|
||
let key = match key_guard.as_ref() {
|
||
Some(key) => key,
|
||
None => {
|
||
shared.push_event(format!("error:{}:no-key", kind));
|
||
return;
|
||
}
|
||
};
|
||
let receiver_slot = if kind == "video" { &shared.video_receiver } else { &shared.audio_receiver };
|
||
let result = match receiver_slot.lock() {
|
||
Ok(mut receiver) => receiver.receive(key, data),
|
||
Err(_) => return,
|
||
};
|
||
// Keep the key slot locked through queue publication so an old session's
|
||
// final packet cannot be enqueued after a concurrent rekey clears queues.
|
||
match result {
|
||
Ok(Some(packet)) => {
|
||
if (kind == "audio") != (packet.flags & crate::media::FLAG_AUDIO != 0) {
|
||
shared.push_event(format!("error:{}:wrong-stream", kind));
|
||
return;
|
||
}
|
||
if kind == "video" {
|
||
if let Some((pts, flags, payload)) =
|
||
reassembler.push(packet.pts, packet.flags, &packet.payload)
|
||
{
|
||
shared.push_event(format!(
|
||
"{}:pts={}:flags={}:bytes={}:from={}",
|
||
kind,
|
||
pts,
|
||
flags,
|
||
payload.len(),
|
||
source
|
||
));
|
||
crate::media::stream::push(pts, flags, &payload);
|
||
}
|
||
} else if packet.flags & crate::media::FLAG_PCM != 0 {
|
||
// PCM 直接进播放队列,桌面端原生播放器按需取走。
|
||
let queued = crate::media::audio::push(&packet.payload);
|
||
shared.push_event(format!(
|
||
"audio:pts={}:bytes={}:queued={}:from={}",
|
||
packet.pts,
|
||
packet.payload.len(),
|
||
queued,
|
||
source
|
||
));
|
||
} else {
|
||
// 旧版对端发的是 Opus;没有解码器时明确丢弃,避免当 PCM 播出噪音。
|
||
shared.push_event(format!(
|
||
"audio:dropped:codec=opus:bytes={}:from={}",
|
||
packet.payload.len(),
|
||
source
|
||
));
|
||
}
|
||
}
|
||
Ok(None) => {}, // authenticated, awaiting the remaining fragments
|
||
Err(error) => shared.push_event(format!("error:{}:{}", kind, error)),
|
||
}
|
||
}
|
||
|
||
/// 中继媒体分片在 v2 已加密媒体包外再套一层 AES-256-GCM:
|
||
/// `[nonce:12][密文][tag:16]`,AAD 固定为 `relay-media`。
|
||
fn decrypt_relay_media(key: &[u8; 32], data: &[u8]) -> Option<Vec<u8>> {
|
||
if data.len() < crate::crypto::NONCE_LEN + crate::crypto::TAG_LEN {
|
||
return None;
|
||
}
|
||
let mut nonce = [0u8; crate::crypto::NONCE_LEN];
|
||
nonce.copy_from_slice(&data[..crate::crypto::NONCE_LEN]);
|
||
crate::crypto::decrypt(
|
||
key,
|
||
&nonce,
|
||
&data[crate::crypto::NONCE_LEN..],
|
||
b"relay-media",
|
||
)
|
||
.ok()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod outbound_tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn blocked_network_writer_does_not_block_enqueue_and_queue_is_bounded() {
|
||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||
let _peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||
let (stream, _) = listener.accept().unwrap();
|
||
let stream = Arc::new(Mutex::new(stream));
|
||
let blocked = stream.lock().unwrap();
|
||
let shared = Arc::new(Shared::new());
|
||
let sender = ControlSender::new(ControlSink::Tcp(stream.clone()), Arc::new(SecureControlChannel::new([3; 32])), &shared);
|
||
let start = Instant::now();
|
||
let mut accepted = 0;
|
||
for sequence in 0..1000 {
|
||
if sender.outbound.try_send(ControlEvent::new(sequence, ControlEventKind::Ping(1))).is_err() { break; }
|
||
accepted += 1;
|
||
}
|
||
assert!((128..=129).contains(&accepted));
|
||
assert!(start.elapsed() < Duration::from_millis(200), "enqueue waited for network IO");
|
||
drop(blocked);
|
||
}
|
||
|
||
#[test]
|
||
fn queued_control_preserves_order_and_uses_distinct_nonces() {
|
||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||
let mut peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||
peer.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
|
||
let (stream, _) = listener.accept().unwrap();
|
||
let shared = Arc::new(Shared::new());
|
||
let channel = Arc::new(SecureControlChannel::new([4; 32]));
|
||
let sender = ControlSender::new(ControlSink::Tcp(Arc::new(Mutex::new(stream))), channel.clone(), &shared);
|
||
for sequence in 1..=2 {
|
||
sender.outbound.try_send(ControlEvent::new(sequence, ControlEventKind::Ping(sequence as u64))).unwrap();
|
||
}
|
||
let mut bytes = [0u8; 88]; // two encrypted Ping frames (8+12+8+16)
|
||
peer.read_exact(&mut bytes).unwrap();
|
||
let (first, consumed) = channel.decode(&bytes).unwrap().unwrap();
|
||
let (second, _) = channel.decode(&bytes[consumed..]).unwrap().unwrap();
|
||
assert_eq!((first.sequence(), second.sequence()), (1, 2));
|
||
assert_ne!(&bytes[8..20], &bytes[consumed+8..consumed+20]);
|
||
}
|
||
}
|