Files
TTSTDConnect/rust_core/src/ffi.rs
T
tongtong e2020ab595 feat: 控制通道接入 TLS 并按自签证书指纹校验
- rust_core:PinnedTlsStream 增加指纹校验、accept、读超时与关闭;会话层新增客户端连接入口
- rust_core:demo 服务按指纹选择 TLS 或明文(首字节 0x16 判定),新增 ttstd_demo_set_tls_fingerprint(ABI 5)
- rust_core:发现结构补齐 tls_fingerprint,mDNS TXT 收发 tls=,信标 JSON 序列化 tls
- android_receiver:新增 TlsIdentity 生成并持久化 P-256 自签证书,TlsServerTransport 用 SSLEngine 包装 Socket
- android_receiver:被控端反连时窥探首字节决定 TLS/明文,信标与配对码公布 tls 指纹
- flutter_sender:NativeCore 暴露 setTlsFingerprint,连接前按目标设备指纹设置,为空则明文
- docs:README 补充 TLS 角色反转、tls 字段与 fp/tls 的区别
2026-11-27 20:35:48 +08:00

637 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! C ABI 出口:供 Flutter(dart:ffi) 与其他原生端调用核心协议能力。
//! 该函数集只暴露无状态的密码学/编解码原语;会话状态由调用方持有。
use std::ffi::c_char;
use std::slice;
use crate::control::{ControlEvent, ControlEventKind, SecureControlChannel};
use crate::crypto::{derive_subkey, encrypt, EphemeralKeyPair};
use crate::media::{decode_media_packet, encode_media_packet, MediaPacket};
/// 输出缓冲区不足。
pub const ERR_BUFFER_TOO_SMALL: i32 = -1;
/// 输入参数非法(空指针、长度错误等)。
pub const ERR_INVALID_ARGUMENT: i32 = -2;
/// 密码学操作失败。
pub const ERR_CRYPTO: i32 = -3;
/// 编解码失败。
pub const ERR_CODEC: i32 = -4;
/// 成功。
pub const OK: i32 = 0;
unsafe fn copy_out(data: &[u8], out: *mut u8, capacity: usize) -> i32 {
if out.is_null() || capacity < data.len() {
return ERR_BUFFER_TOO_SMALL;
}
slice::from_raw_parts_mut(out, data.len()).copy_from_slice(data);
data.len() as i32
}
unsafe fn read_slice<'a>(ptr: *const u8, len: usize) -> Result<&'a [u8], i32> {
if ptr.is_null() && len > 0 {
Err(ERR_INVALID_ARGUMENT)
} else {
Ok(slice::from_raw_parts(ptr, len))
}
}
unsafe fn read_key(ptr: *const u8) -> Result<[u8; 32], i32> {
let bytes = read_slice(ptr, 32)?;
let mut key = [0u8; 32];
key.copy_from_slice(bytes);
Ok(key)
}
/// 返回 Rust Core 版本号字符串(静态内存,调用方不要释放)。
#[no_mangle]
pub extern "C" fn ttstd_core_version() -> *const c_char {
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
}
/// 生成 ECDH P-256 临时密钥对,公钥(65 字节非压缩形式)写入 out_public。
/// 返回非负句柄(i64,避免 64 位指针截断),调用方必须用 ttstd_ecdh_free 释放。
///
/// # Safety
/// out_public 必须可写且容量 >= 65。
#[no_mangle]
pub unsafe extern "C" fn ttstd_ecdh_generate(out_public: *mut u8, capacity: usize) -> i64 {
let pair = match EphemeralKeyPair::generate() {
Ok(pair) => pair,
Err(_) => return ERR_CRYPTO as i64,
};
let public = pair.public_bytes().to_vec();
let written = copy_out(&public, out_public, capacity);
if written < 0 {
return written as i64;
}
Box::into_raw(Box::new(pair)) as i64
}
/// 完成 ECDH 协商并把 32 字节共享密钥写入 out_secret。返回写入字节数或错误码。
/// 调用后句柄即被消费,无需再调用 ttstd_ecdh_free。
///
/// # Safety
/// handle 必须来自 ttstd_ecdh_generate 且尚未释放;peer_public 长度必须为 65。
#[no_mangle]
pub unsafe extern "C" fn ttstd_ecdh_agree(
handle: i64,
peer_public: *const u8,
peer_len: usize,
out_secret: *mut u8,
capacity: usize,
) -> i32 {
if handle <= 0 {
return ERR_INVALID_ARGUMENT;
}
let pair = Box::from_raw(handle as *mut EphemeralKeyPair);
let peer = match read_slice(peer_public, peer_len) {
Ok(bytes) => bytes,
Err(code) => return code,
};
let secret = match pair.into_shared_secret(peer) {
Ok(value) => value,
Err(_) => return ERR_CRYPTO,
};
copy_out(&secret, out_secret, capacity)
}
/// 释放 ttstd_ecdh_generate 返回的句柄。
///
/// # Safety
/// handle 必须是有效的、未释放的句柄。
#[no_mangle]
pub unsafe extern "C" fn ttstd_ecdh_free(handle: i64) {
if handle > 0 {
drop(Box::from_raw(handle as *mut EphemeralKeyPair));
}
}
/// HKDF-SHA256 子密钥派生:secret + label -> 32 字节子密钥。
#[no_mangle]
pub unsafe extern "C" fn ttstd_derive_subkey(
secret: *const u8,
secret_len: usize,
label: *const u8,
label_len: usize,
out_key: *mut u8,
capacity: usize,
) -> i32 {
let secret = match read_slice(secret, secret_len) {
Ok(value) => value,
Err(code) => return code,
};
let label = match read_slice(label, label_len) {
Ok(value) => value,
Err(code) => return code,
};
let key = match derive_subkey(secret, label) {
Ok(value) => value,
Err(_) => return ERR_CRYPTO,
};
copy_out(&key, out_key, capacity)
}
/// AES-256-GCM 加密:out = ciphertext || tag(16)。
#[no_mangle]
pub unsafe extern "C" fn ttstd_aes_encrypt(
key: *const u8,
nonce: *const u8,
plaintext: *const u8,
plaintext_len: usize,
aad: *const u8,
aad_len: usize,
out: *mut u8,
capacity: usize,
) -> i32 {
let key = match read_key(key) {
Ok(value) => value,
Err(code) => return code,
};
let nonce_bytes = match read_slice(nonce, 12) {
Ok(value) => value,
Err(code) => return code,
};
let mut nonce = [0u8; 12];
nonce.copy_from_slice(nonce_bytes);
let plaintext = match read_slice(plaintext, plaintext_len) {
Ok(value) => value,
Err(code) => return code,
};
let aad = match read_slice(aad, aad_len) {
Ok(value) => value,
Err(code) => return code,
};
let cipher = match encrypt(&key, &nonce, plaintext, aad) {
Ok(value) => value,
Err(_) => return ERR_CRYPTO,
};
copy_out(&cipher, out, capacity)
}
/// 媒体包封装:13 字节头 + payload + 4 字节截断 HMAC。
#[no_mangle]
pub unsafe extern "C" fn ttstd_media_encode(
pts: u64,
flags: u8,
key: *const u8,
payload: *const u8,
payload_len: usize,
out: *mut u8,
capacity: usize,
) -> i32 {
let key = match read_key(key) {
Ok(value) => value,
Err(code) => return code,
};
let payload = match read_slice(payload, payload_len) {
Ok(value) => value,
Err(code) => return code,
};
let packet = encode_media_packet(
&MediaPacket {
pts,
flags,
payload: payload.to_vec(),
},
&key,
);
copy_out(&packet, out, capacity)
}
/// 媒体包解析与 MAC 校验。成功时把解析结果写到 out_packet(JSON UTF-8)。
#[no_mangle]
pub unsafe extern "C" fn ttstd_media_decode(
buffer: *const u8,
buffer_len: usize,
key: *const u8,
out_json: *mut u8,
capacity: usize,
) -> i32 {
let buffer = match read_slice(buffer, buffer_len) {
Ok(value) => value,
Err(code) => return code,
};
let key = match read_key(key) {
Ok(value) => value,
Err(code) => return code,
};
let decoded = match decode_media_packet(buffer, &key) {
Ok(Some(value)) => value,
Ok(None) => return ERR_CODEC,
Err(_) => return ERR_CRYPTO,
};
let (packet, _) = decoded;
let json = format!(
"{{\"pts\":{},\"flags\":{},\"payloadLen\":{}}}",
packet.pts,
packet.flags,
packet.payload.len()
);
copy_out(json.as_bytes(), out_json, capacity)
}
/// 创建安全控制通道句柄(持 32 字节密钥与发送计数器)。
#[no_mangle]
pub unsafe extern "C" fn ttstd_control_channel_new(key: *const u8) -> i64 {
let key = match read_key(key) {
Ok(value) => value,
Err(code) => return code as i64,
};
Box::into_raw(Box::new(SecureControlChannel::new(key))) as i64
}
/// 释放安全控制通道句柄。
#[no_mangle]
pub unsafe extern "C" fn ttstd_control_channel_free(handle: i64) {
if handle > 0 {
drop(Box::from_raw(handle as *mut SecureControlChannel));
}
}
/// 编码 Ping 控制帧(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。
#[no_mangle]
pub unsafe extern "C" fn ttstd_control_encode_ping(
handle: i64,
sequence: u16,
timestamp: u64,
out: *mut u8,
capacity: usize,
) -> i32 {
if handle <= 0 {
return ERR_INVALID_ARGUMENT;
}
let channel = &*(handle as *const SecureControlChannel);
let event = ControlEvent::new(sequence, ControlEventKind::Ping(timestamp));
let frame = match channel.encode(&event) {
Ok(value) => value,
Err(_) => return ERR_CRYPTO,
};
copy_out(&frame, out, capacity)
}
/// 解码安全控制帧,成功时把事件写到 out_json。
#[no_mangle]
pub unsafe extern "C" fn ttstd_control_decode(
handle: i64,
buffer: *const u8,
buffer_len: usize,
out_json: *mut u8,
capacity: usize,
) -> i32 {
if handle <= 0 {
return ERR_INVALID_ARGUMENT;
}
let channel = &*(handle as *const SecureControlChannel);
let buffer = match read_slice(buffer, buffer_len) {
Ok(value) => value,
Err(code) => return code,
};
let decoded = match channel.decode(buffer) {
Ok(Some(value)) => value,
Ok(None) => return ERR_CODEC,
Err(_) => return ERR_CRYPTO,
};
let (event, _) = decoded;
let kind = match event.kind {
ControlEventKind::Ping(_) => "ping",
ControlEventKind::Pong(_) => "pong",
ControlEventKind::Touch(_) => "touch",
ControlEventKind::Mouse(_) => "mouse",
ControlEventKind::Key(_) => "key",
ControlEventKind::Wheel(_) => "wheel",
ControlEventKind::Clipboard(_) => "clipboard",
ControlEventKind::Mirror(_) => "mirror",
ControlEventKind::Config(_) => "config",
ControlEventKind::File(_) => "file",
};
let json = format!(
"{{\"sequence\":{},\"msgType\":{},\"kind\":\"{}\"}}",
event.sequence(),
event.msg_type(),
kind
);
copy_out(json.as_bytes(), out_json, capacity)
}
/// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。
/// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE)
/// 8=mirror([action:u8]+文本) 9=sessionConfig(UTF-8 JSON)
#[no_mangle]
pub unsafe extern "C" fn ttstd_demo_send_control(
sequence: u16,
msg_type: u8,
payload: *const u8,
payload_len: usize,
) -> i32 {
use crate::control::events::MSG_CLIPBOARD;
let bytes = match read_slice(payload, payload_len) {
Ok(value) => value,
Err(code) => return code,
};
let event = match msg_type {
0 if bytes.len() == 8 => crate::demo_server::touch_event(
sequence, bytes[0], bytes[1],
i16::from_le_bytes([bytes[2], bytes[3]]),
i16::from_le_bytes([bytes[4], bytes[5]]),
u16::from_le_bytes([bytes[6], bytes[7]]),
),
1 if bytes.len() == 6 => crate::demo_server::mouse_event(
sequence, bytes[0],
i16::from_le_bytes([bytes[1], bytes[2]]),
i16::from_le_bytes([bytes[3], bytes[4]]),
bytes[5],
),
2 if bytes.len() == 5 => crate::demo_server::key_event(
sequence, bytes[0],
u16::from_le_bytes([bytes[1], bytes[2]]),
u16::from_le_bytes([bytes[3], bytes[4]]),
),
3 if bytes.len() == 5 => Some(crate::demo_server::wheel_event(
sequence,
i16::from_le_bytes([bytes[0], bytes[1]]),
i16::from_le_bytes([bytes[2], bytes[3]]),
bytes[4],
)),
MSG_CLIPBOARD => Some(crate::demo_server::clipboard_event(
sequence,
String::from_utf8_lossy(bytes).to_string(),
)),
5 if bytes.len() == 8 => Some(crate::demo_server::ping_event(
sequence,
u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]),
)),
// 8 = 投屏请求/停止:[action:u8] + 可选 UTF-8 说明
8 if !bytes.is_empty() => Some(crate::demo_server::mirror_event(
sequence,
bytes[0],
String::from_utf8_lossy(&bytes[1..]).to_string(),
)),
// 9 = 会话配置:payload 就是 UTF-8 JSON
9 => Some(crate::demo_server::config_event(
sequence,
String::from_utf8_lossy(bytes).to_string(),
)),
_ => None,
};
match event {
Some(event) => match crate::demo_server::send_control(event) {
Ok(()) => OK,
Err(_) => ERR_INVALID_ARGUMENT,
},
None => ERR_INVALID_ARGUMENT,
}
}
/// 启动本机 demo 服务:TCP 控制 + UDP 视频/音频。
#[no_mangle]
pub extern "C" fn ttstd_demo_start(control_port: u16, video_port: u16, audio_port: u16) -> i32 {
match crate::demo_server::start(control_port, video_port, audio_port) {
Ok(()) => OK,
Err(_) => ERR_INVALID_ARGUMENT,
}
}
/// 停止本机 demo 服务。
#[no_mangle]
pub extern "C" fn ttstd_demo_stop() {
crate::demo_server::stop();
}
/// 设置控制通道 TLS 所需的对端证书指纹(空串表示对端不支持 TLS,走明文)。
///
/// # Safety
/// fingerprint 指向长度为 len 的 UTF-8 字节。
#[no_mangle]
pub unsafe extern "C" fn ttstd_demo_set_tls_fingerprint(
fingerprint: *const u8,
len: usize,
) -> i32 {
let bytes = match read_slice(fingerprint, len) {
Ok(bytes) => bytes,
Err(code) => return code,
};
let text = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => return ERR_INVALID_ARGUMENT,
};
crate::demo_server::set_tls_fingerprint(text);
OK
}
/// 通过信令服务器建立中继控制会话(跨网段、无端口映射时使用)。
///
/// 中继只承载控制通道,视频/音频仍走 UDP 直连,因此中继模式下不能投屏。
/// 结果统一写成 JSON:成功 `{"ok":true}`,失败 `{"error":"原因"}`。
///
/// # Safety
/// base_url / peer_id 分别指向对应长度的 UTF-8 字节;out_json 可写且容量为 capacity。
#[no_mangle]
pub unsafe extern "C" fn ttstd_relay_start(
base_url: *const u8,
base_url_len: usize,
peer_id: *const u8,
peer_id_len: usize,
out_json: *mut u8,
capacity: usize,
) -> i32 {
let result = (|| -> Result<(), String> {
let url = read_slice(base_url, base_url_len).map_err(|_| "信令地址非法".to_string())?;
let peer = read_slice(peer_id, peer_id_len).map_err(|_| "设备 id 非法".to_string())?;
let url = std::str::from_utf8(url).map_err(|_| "信令地址不是 UTF-8".to_string())?;
let peer = std::str::from_utf8(peer).map_err(|_| "设备 id 不是 UTF-8".to_string())?;
crate::demo_server::start_relay(url, peer)
})();
let json = match result {
Ok(()) => "{\"ok\":true}".to_string(),
Err(message) => format!("{{\"error\":\"{}\"}}", message.replace('"', "'")),
};
copy_out(json.as_bytes(), out_json, capacity)
}
/// 停止中继会话(直连控制通道不受影响)。
#[no_mangle]
pub extern "C" fn ttstd_relay_stop() {
crate::demo_server::stop_relay();
}
/// 获取 demo 服务状态 JSON。
#[no_mangle]
pub unsafe extern "C" fn ttstd_demo_status(out_json: *mut u8, capacity: usize) -> i32 {
let json = crate::demo_server::status().to_json();
copy_out(json.as_bytes(), out_json, capacity)
}
/// 取出一个待处理的上行控制事件 JSON:`{"type":8,"action":2,"text":"..."}`。
///
/// - 返回正数:写入 `out_json` 的字节数,事件已出队。
/// - 返回 `0`:队列为空。
/// - 返回 [`ERR_BUFFER_TOO_SMALL`]:容量不足,事件**保留**在队列中。
///
/// # Safety
/// out_json 可写且容量为 capacity。
#[no_mangle]
pub unsafe extern "C" fn ttstd_event_next(out_json: *mut u8, capacity: usize) -> i32 {
let Some(json) = crate::demo_server::peek_inbound_event() else {
return 0;
};
let written = copy_out(json.as_bytes(), out_json, capacity);
if written >= 0 {
crate::demo_server::pop_inbound_event();
}
written
}
/// 视频访问单元元信息。字段布局需与 Windows 原生解码侧保持一致。
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]
pub struct TtstdVideoFrame {
/// 访问单元序号,单调递增。
pub seq: u64,
/// 呈现时间戳(微秒)。
pub pts: u64,
/// 负载字节数。
pub len: u32,
/// 负载格式:1=H.264 Annex-B,2=HEVC Annex-B。
pub format: u8,
/// 媒体包标志位(bit0=关键帧)。
pub flags: u8,
/// 对齐保留字段。
pub reserved: u16,
}
/// 当前待解码的访问单元数量。
#[no_mangle]
pub extern "C" fn ttstd_video_pending() -> u32 {
crate::media::stream::stats().queued as u32
}
/// 读取队首视频访问单元。
///
/// - 返回 `0`:队列为空。
/// - 返回正数:实际写入 `out` 的字节数,该访问单元已出队。
/// - 返回 `ERR_BUFFER_TOO_SMALL`:`out` 容量不足,`meta` 已写入所需长度,访问单元保留在队列中。
///
/// # Safety
/// meta 必须可写;out 可写且容量为 capacity。
#[no_mangle]
pub unsafe extern "C" fn ttstd_video_next(
meta: *mut TtstdVideoFrame,
out: *mut u8,
capacity: usize,
) -> i32 {
let Some(front) = crate::media::stream::peek_meta() else {
return 0;
};
if !meta.is_null() {
*meta = TtstdVideoFrame {
seq: front.seq,
pts: front.pts,
len: front.len as u32,
format: front.format,
flags: front.flags,
reserved: 0,
};
}
if out.is_null() || capacity < front.len {
return ERR_BUFFER_TOO_SMALL;
}
let buffer = slice::from_raw_parts_mut(out, front.len);
match crate::media::stream::pop_into(front.seq, buffer) {
Some(taken) => taken.len as i32,
None => 0,
}
}
/// 视频队列统计 JSON(诊断用)。
#[no_mangle]
pub unsafe extern "C" fn ttstd_video_stats(out_json: *mut u8, capacity: usize) -> i32 {
let json = crate::media::stream::stats_json();
copy_out(json.as_bytes(), out_json, capacity)
}
/// 启动同网段自动发现(UDP 41003)。幂等:已在运行时直接返回 OK。
#[no_mangle]
pub extern "C" fn ttstd_discovery_start(
control_port: u16,
media_port: u16,
audio_port: u16,
) -> i32 {
if crate::discovery::beacon::start(control_port, media_port, audio_port) {
// mDNS 浏览与信标并行:任一命中都能出现在设备列表里。
crate::discovery::mdns::start_browsing();
OK
} else {
ERR_INVALID_ARGUMENT
}
}
/// 已发现设备列表 JSON:`{"devices":[...]}`,字段与信令 `/list` 一致。
#[no_mangle]
pub unsafe extern "C" fn ttstd_discovery_devices(out_json: *mut u8, capacity: usize) -> i32 {
let json = crate::discovery::merged_devices_json();
copy_out(json.as_bytes(), out_json, capacity)
}
/// 通知指定 IP 的被控端「主控端已就绪」,被控端据此拨号。
///
/// # Safety
/// ip 必须指向长度为 len 的 UTF-8 字节。
#[no_mangle]
pub unsafe extern "C" fn ttstd_discovery_connect(ip: *const u8, len: usize) -> i32 {
let bytes = match read_slice(ip, len) {
Ok(bytes) => bytes,
Err(code) => return code,
};
let text = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => return ERR_INVALID_ARGUMENT,
};
if crate::discovery::beacon::connect(text) {
OK
} else {
ERR_INVALID_ARGUMENT
}
}
/// 文件子协议(msgType=7):把 JSON 请求发给被控端,把响应原样写回 out_json。
///
/// 请求/响应字段由子协议定义(`op=prepare|chunk|progress|cancel|list`),
/// 二进制分片在 Dart 侧做 base64 后放进 `dataB64`,这里不解析内容。
/// 失败时同样返回 JSON(`{"error":"..."}`),便于界面直接展示原因。
#[no_mangle]
pub unsafe extern "C" fn ttstd_file_request(
request: *const u8,
request_len: usize,
out_json: *mut u8,
capacity: usize,
) -> i32 {
let bytes = match read_slice(request, request_len) {
Ok(value) => value,
Err(code) => return code,
};
let json = match std::str::from_utf8(bytes) {
Ok(text) => text.to_string(),
Err(_) => return ERR_INVALID_ARGUMENT,
};
let response = match crate::demo_server::request_file(json, std::time::Duration::from_secs(5)) {
Ok(response) => response,
Err(message) => format!("{{\"error\":\"{}\"}}", message.replace('"', "'")),
};
copy_out(response.as_bytes(), out_json, capacity)
}
/// 停止自动发现(退出或测试用)。
#[no_mangle]
pub extern "C" fn ttstd_discovery_stop() {
crate::discovery::beacon::stop();
crate::discovery::mdns::stop_browsing();
}
/// ABI 版本,便于 Dart 侧校验动态库是否匹配。
#[no_mangle]
pub extern "C" fn ttstd_core_abi_revision() -> i32 {
5
}