feat(core): 增加 mDNS 常驻浏览、文件子协议与信令中继
- mDNS 常驻浏览并与 UDP 信标按 ip+控制端口合并,信标优先 - TXT 解析 id/cport,缺失时回落 ip+41001 - 新增 ttstd_file_request(msgType=7 一问一答,5s 超时)与 base64 工具 - 新增 session/relay.rs:relay/1 信封、hs/hsAck/frame/bye、对端过滤 - demo_server 控制写端抽象为 TCP/中继两种,修复双编码器 nonce 复用 - 新增 ttstd_relay_start/stop,ABI 版本升到 4 - 单测覆盖信封往返与本地假信令服务器上的收发过滤
This commit is contained in:
1 parent
c5ace8c179
commit
2bf102c543
11 files changed
+1167
-96
No files matched your search
+458
-65
@@ -9,30 +9,39 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream, UdpSocket};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::control::events::{
|
||||
ClipboardEvent, ConfigEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction, MouseEvent,
|
||||
TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_MIRROR,
|
||||
ClipboardEvent, ConfigEvent, FileEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction,
|
||||
MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_MIRROR,
|
||||
};
|
||||
use crate::control::{ControlEvent, ControlEventKind};
|
||||
|
||||
use crate::control::SecureControlChannel;
|
||||
use crate::crypto::{derive_subkey, EphemeralKeyPair};
|
||||
use crate::media::decode_media_packet;
|
||||
use crate::session::relay::{self, RelayChannel, RelayMessage};
|
||||
|
||||
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,
|
||||
@@ -52,11 +61,12 @@ impl DemoStatus {
|
||||
.join(",");
|
||||
format!(
|
||||
concat!(
|
||||
"{{\"running\":{},\"peerConnected\":{},\"keyEstablished\":{},",
|
||||
"{{\"running\":{},\"relay\":{},\"peerConnected\":{},\"keyEstablished\":{},",
|
||||
"\"peerIp\":\"{}\",\"controlKey\":\"{}\",\"videoKey\":\"{}\",",
|
||||
"\"audioKey\":\"{}\",\"events\":[{}]}}"
|
||||
),
|
||||
self.running,
|
||||
self.relay,
|
||||
self.peer_connected,
|
||||
self.key_established,
|
||||
self.peer_ip.replace('"', ""),
|
||||
@@ -68,9 +78,47 @@ impl DemoStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// 控制帧写端:直连写 TCP,跨网段写信令中继。
|
||||
#[derive(Clone)]
|
||||
enum ControlSink {
|
||||
Tcp(Arc<Mutex<TcpStream>>),
|
||||
Relay(Arc<RelayChannel>),
|
||||
}
|
||||
|
||||
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)),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_relay(&self) -> bool {
|
||||
matches!(self, Self::Relay(_))
|
||||
}
|
||||
|
||||
/// 只对 TCP 生效:打断阻塞中的读,让控制连接尽快退出。
|
||||
fn shutdown(&self) {
|
||||
if let Self::Tcp(stream) = self {
|
||||
if let Ok(stream) = stream.lock() {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlSender {
|
||||
stream: Arc<Mutex<TcpStream>>,
|
||||
channel: SecureControlChannel,
|
||||
sink: ControlSink,
|
||||
/// 与读循环共用同一个实例,避免两条编码路径各自从 counter=1 起算造成 nonce 复用。
|
||||
channel: Arc<SecureControlChannel>,
|
||||
}
|
||||
|
||||
/// 被控端上行的控制事件(mirror 应答 / 剪贴板),供 UI 侧轮询消费。
|
||||
@@ -113,6 +161,8 @@ fn escape_json(text: &str) -> String {
|
||||
|
||||
struct Shared {
|
||||
running: AtomicBool,
|
||||
/// 中继会话线程是否在跑(与直连控制通道互斥使用 `sender`)。
|
||||
relay_running: AtomicBool,
|
||||
peer_connected: AtomicBool,
|
||||
key_established: AtomicBool,
|
||||
peer_ip: Mutex<String>,
|
||||
@@ -122,12 +172,15 @@ struct Shared {
|
||||
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()),
|
||||
@@ -137,6 +190,7 @@ impl Shared {
|
||||
sender: Mutex::new(None),
|
||||
events: Mutex::new(Vec::new()),
|
||||
inbound: Mutex::new(VecDeque::new()),
|
||||
file_responses: Mutex::new(VecDeque::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,6 +219,31 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -180,6 +259,7 @@ impl Shared {
|
||||
};
|
||||
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(),
|
||||
@@ -194,6 +274,8 @@ impl Shared {
|
||||
struct ServerHandle {
|
||||
shared: Arc<Shared>,
|
||||
threads: Mutex<Vec<JoinHandle<()>>>,
|
||||
/// 中继会话线程单独保存:中继与直连可以同时存在,不能一起 join。
|
||||
relay_thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
static SERVER: OnceLock<ServerHandle> = OnceLock::new();
|
||||
@@ -202,6 +284,7 @@ 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),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -221,19 +304,28 @@ fn join_threads(handle: &ServerHandle) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 回收上一轮中继线程。轮询带 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 stream = shared
|
||||
let sender = shared
|
||||
.sender
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut guard| guard.take())
|
||||
.map(|sender| sender.stream);
|
||||
if let Some(stream) = stream {
|
||||
if let Ok(stream) = stream.lock() {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Both);
|
||||
}
|
||||
.and_then(|mut guard| guard.take());
|
||||
if let Some(sender) = sender {
|
||||
sender.sink.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +340,9 @@ fn reset_session_state(shared: &Shared) {
|
||||
}
|
||||
}
|
||||
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() {
|
||||
@@ -329,8 +424,10 @@ pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(),
|
||||
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() {
|
||||
@@ -344,6 +441,264 @@ pub fn status() -> DemoStatus {
|
||||
server_handle().shared.status()
|
||||
}
|
||||
|
||||
/// 通过信令服务器建立中继控制会话(跨网段、无端口映射时使用)。
|
||||
///
|
||||
/// 中继只承载控制通道:视频/音频仍走 UDP 直连,因此中继模式下不能投屏。
|
||||
/// 幂等:重复调用会先停掉上一轮中继,再按新参数重连。
|
||||
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());
|
||||
}
|
||||
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 {
|
||||
sink: sink.clone(),
|
||||
channel: Arc::clone(&control_channel),
|
||||
});
|
||||
}
|
||||
|
||||
let mut buffer: Vec<u8> = Vec::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::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);
|
||||
}
|
||||
|
||||
/// 查看队首的上行事件(mirror 应答 / 剪贴板)JSON,队列空时返回 None。
|
||||
///
|
||||
/// 与 [`pop_inbound_event`] 配对使用:调用方先把 JSON 拷进自己的缓冲,再出队,
|
||||
@@ -362,6 +717,27 @@ pub fn pop_inbound_event() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 发送一条文件子协议请求(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(()) 表示已写入 TCP,Err 表示未连接或写入失败。
|
||||
pub fn send_control(event: ControlEvent) -> Result<(), String> {
|
||||
@@ -376,14 +752,7 @@ pub fn send_control(event: ControlEvent) -> Result<(), String> {
|
||||
.channel
|
||||
.encode(&event)
|
||||
.map_err(|error| format!("控制帧加密失败:{}", error))?;
|
||||
let mut stream = sender
|
||||
.stream
|
||||
.lock()
|
||||
.map_err(|_| "控制写端锁不可用".to_string())?;
|
||||
stream
|
||||
.write_all(&frame)
|
||||
.and_then(|_| stream.flush())
|
||||
.map_err(|error| format!("控制帧下发失败:{}", error))?;
|
||||
sender.sink.send(&frame)?;
|
||||
handle.shared.push_event(format!(
|
||||
"sent:seq={}:type={}",
|
||||
event.sequence(),
|
||||
@@ -438,6 +807,11 @@ pub fn ping_event(sequence: u16, timestamp: u64) -> ControlEvent {
|
||||
}
|
||||
|
||||
/// 构造投屏请求/停止事件(主控端 → 被控端)。
|
||||
/// 构造文件子协议事件(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 }))
|
||||
}
|
||||
@@ -451,6 +825,12 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
|
||||
while shared.running.load(Ordering::Relaxed) {
|
||||
match listener.accept() {
|
||||
Ok((mut 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);
|
||||
if let Ok(mut ip) = shared.peer_ip.lock() {
|
||||
@@ -528,14 +908,18 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
// 握手完成,恢复正常读超时(兼作心跳周期)。
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
|
||||
|
||||
let channel = SecureControlChannel::new(control);
|
||||
if let Ok(write_stream) = stream.try_clone() {
|
||||
if let Ok(mut guard) = shared.sender.lock() {
|
||||
*guard = Some(ControlSender {
|
||||
stream: Arc::new(Mutex::new(write_stream)),
|
||||
channel: SecureControlChannel::new(control),
|
||||
});
|
||||
}
|
||||
// 编解码共用一个实例: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 {
|
||||
sink: sink.clone(),
|
||||
channel: Arc::clone(&channel),
|
||||
});
|
||||
}
|
||||
let mut buffer = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
@@ -561,11 +945,10 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
let Ok(frame) = channel.encode(&ping) else {
|
||||
continue;
|
||||
};
|
||||
if stream.write_all(&frame).is_err() {
|
||||
if sink.send(&frame).is_err() {
|
||||
shared.push_event("control:keepalive-write-error".to_string());
|
||||
break;
|
||||
}
|
||||
let _ = stream.flush();
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -581,40 +964,8 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
loop {
|
||||
match channel.decode(&buffer) {
|
||||
Ok(Some((event, consumed))) => {
|
||||
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::Clipboard(clipboard) => {
|
||||
shared.push_inbound(InboundEvent {
|
||||
msg_type: MSG_CLIPBOARD,
|
||||
action: 0,
|
||||
text: clipboard.text.clone(),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
buffer.drain(..consumed);
|
||||
if let crate::control::ControlEventKind::Ping(timestamp) = event.kind {
|
||||
let pong = crate::control::ControlEvent::new(
|
||||
event.sequence(),
|
||||
crate::control::ControlEventKind::Pong(timestamp),
|
||||
);
|
||||
if let Ok(frame) = channel.encode(&pong) {
|
||||
let _ = stream.write_all(&frame);
|
||||
let _ = stream.flush();
|
||||
}
|
||||
}
|
||||
dispatch_control_event(shared, &event, &channel, &sink);
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
@@ -627,6 +978,48 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 处理一帧已解出的控制事件:把界面要处理的事件入队,并回 `pong`。
|
||||
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::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 分片,这里按序重组。
|
||||
|
||||
Reference in new issue
Block a user