mirror of
https://github.com/mofeng-git/One-KVM.git
synced 2026-09-13 02:54:26 +08:00
feat(rustdesk): 新增独占式 IP 直连模式
This commit is contained in:
@@ -121,7 +121,7 @@ impl RemoteAccessCoordinator {
|
||||
let vnc = self.vnc.read().await.clone();
|
||||
let rtsp = self.rtsp.read().await.clone();
|
||||
|
||||
config.rustdesk.enabled = rustdesk.is_some_and(|service| service.is_listening());
|
||||
config.rustdesk.enabled = rustdesk.is_some_and(|service| service.is_running());
|
||||
config.vnc.enabled = match vnc {
|
||||
Some(service) => matches!(
|
||||
service.status().await,
|
||||
@@ -191,8 +191,12 @@ impl RemoteAccessCoordinator {
|
||||
.await?;
|
||||
|
||||
let need_restart = options.force
|
||||
|| old_config.mode != new_config.mode
|
||||
|| old_config.codec != new_config.codec
|
||||
|| old_config.direct_access_port != new_config.direct_access_port
|
||||
|| old_config.rendezvous_server != new_config.rendezvous_server
|
||||
|| old_config.relay_server != new_config.relay_server
|
||||
|| old_config.relay_key != new_config.relay_key
|
||||
|| old_config.device_id != new_config.device_id
|
||||
|| old_config.device_password != new_config.device_password;
|
||||
let current = self.rustdesk.read().await.clone();
|
||||
@@ -224,7 +228,7 @@ impl RemoteAccessCoordinator {
|
||||
credentials_to_save = service.save_credentials();
|
||||
}
|
||||
Some(service) => {
|
||||
if service.is_listening() {
|
||||
if service.is_running() {
|
||||
if need_restart {
|
||||
service.restart(new_config.clone()).await.map_err(|error| {
|
||||
AppError::Config(format!(
|
||||
|
||||
@@ -11,12 +11,24 @@ pub enum RustDeskCodec {
|
||||
H265,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[derive(Default)]
|
||||
pub enum RustDeskMode {
|
||||
#[default]
|
||||
Id,
|
||||
DirectIp,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct RustDeskConfig {
|
||||
pub enabled: bool,
|
||||
pub mode: RustDeskMode,
|
||||
pub codec: RustDeskCodec,
|
||||
pub direct_access_port: u16,
|
||||
pub rendezvous_server: String,
|
||||
pub relay_server: Option<String>,
|
||||
#[typeshare(skip)]
|
||||
@@ -40,7 +52,9 @@ impl Default for RustDeskConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
mode: RustDeskMode::Id,
|
||||
codec: RustDeskCodec::H264,
|
||||
direct_access_port: 21118,
|
||||
rendezvous_server: String::new(),
|
||||
relay_server: None,
|
||||
relay_key: None,
|
||||
@@ -58,9 +72,12 @@ impl Default for RustDeskConfig {
|
||||
impl RustDeskConfig {
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.enabled
|
||||
&& !self.rendezvous_server.is_empty()
|
||||
&& !self.device_id.is_empty()
|
||||
&& !self.device_password.is_empty()
|
||||
&& match self.mode {
|
||||
RustDeskMode::Id => !self.rendezvous_server.trim().is_empty(),
|
||||
RustDeskMode::DirectIp => self.direct_access_port != 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn effective_rendezvous_server(&self) -> &str {
|
||||
@@ -214,4 +231,43 @@ mod tests {
|
||||
config.rendezvous_server = String::new();
|
||||
assert_eq!(config.effective_rendezvous_server(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_ip_mode_is_valid_without_rendezvous_server() {
|
||||
let config = RustDeskConfig {
|
||||
enabled: true,
|
||||
mode: RustDeskMode::DirectIp,
|
||||
rendezvous_server: String::new(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(config.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_mode_is_invalid_without_rendezvous_server() {
|
||||
let config = RustDeskConfig {
|
||||
enabled: true,
|
||||
mode: RustDeskMode::Id,
|
||||
rendezvous_server: String::new(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(!config.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_config_defaults_to_id_mode() {
|
||||
let config: RustDeskConfig = serde_json::from_value(serde_json::json!({
|
||||
"enabled": false,
|
||||
"codec": "h264",
|
||||
"rendezvous_server": "",
|
||||
"device_id": "123456789",
|
||||
"device_password": "password"
|
||||
}))
|
||||
.expect("legacy RustDesk config should deserialize");
|
||||
|
||||
assert_eq!(config.mode, RustDeskMode::Id);
|
||||
assert_eq!(config.direct_access_port, 21118);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +100,12 @@ pub enum ConnectionState {
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ConnectionMode {
|
||||
Secure,
|
||||
DirectIp,
|
||||
}
|
||||
|
||||
/// Incoming connection from a RustDesk client
|
||||
pub struct Connection {
|
||||
/// Connection ID
|
||||
@@ -113,12 +119,18 @@ pub struct Connection {
|
||||
/// Connection state
|
||||
state: Arc<RwLock<ConnectionState>>,
|
||||
/// Our signing keypair (Ed25519) for signing SignedId messages
|
||||
signing_keypair: SigningKeyPair,
|
||||
signing_keypair: Option<SigningKeyPair>,
|
||||
/// Temporary Curve25519 keypair for this connection (used for encryption)
|
||||
/// Generated fresh for each connection, public key goes in IdPk.pk
|
||||
temp_keypair: (box_::PublicKey, box_::SecretKey),
|
||||
/// Device password
|
||||
password: String,
|
||||
/// Connection path determines whether the RustDesk signed-ID handshake is used.
|
||||
mode: ConnectionMode,
|
||||
/// Password hashing salt sent to the client.
|
||||
password_salt: String,
|
||||
/// Per-connection challenge prevents replaying a captured password hash.
|
||||
password_challenge: String,
|
||||
/// HID controller for keyboard/mouse events
|
||||
hid: Option<Arc<HidController>>,
|
||||
/// Audio controller for audio streaming
|
||||
@@ -197,7 +209,8 @@ impl Connection {
|
||||
pub fn new(
|
||||
id: u32,
|
||||
config: &RustDeskConfig,
|
||||
signing_keypair: SigningKeyPair,
|
||||
mode: ConnectionMode,
|
||||
signing_keypair: Option<SigningKeyPair>,
|
||||
hid: Option<Arc<HidController>>,
|
||||
audio: Option<Arc<AudioController>>,
|
||||
video_manager: Option<Arc<VideoStreamManager>>,
|
||||
@@ -223,6 +236,9 @@ impl Connection {
|
||||
signing_keypair,
|
||||
temp_keypair,
|
||||
password: config.device_password.clone(),
|
||||
mode,
|
||||
password_salt: config.device_id.clone(),
|
||||
password_challenge: uuid::Uuid::new_v4().simple().to_string(),
|
||||
hid,
|
||||
audio,
|
||||
video_manager,
|
||||
@@ -282,14 +298,27 @@ impl Connection {
|
||||
let writer = Arc::new(Mutex::new(writer));
|
||||
let mut shutdown_rx = self.shutdown_tx.subscribe();
|
||||
|
||||
// Send our SignedId first (this is what RustDesk protocol expects)
|
||||
// The SignedId contains our device ID and temporary public key
|
||||
let signed_id_msg = self.create_signed_id_message(&self.device_id.clone());
|
||||
let signed_id_bytes = signed_id_msg
|
||||
.write_to_bytes()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to encode SignedId: {}", e))?;
|
||||
debug!("Sending SignedId with device_id={}", self.device_id);
|
||||
self.send_framed_arc(&writer, &signed_id_bytes).await?;
|
||||
match self.mode {
|
||||
ConnectionMode::Secure => {
|
||||
// ID-server and relay connections authenticate our ephemeral key through hbbs.
|
||||
let signed_id_msg = self.create_signed_id_message(&self.device_id.clone());
|
||||
let signed_id_bytes = signed_id_msg
|
||||
.write_to_bytes()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to encode SignedId: {}", e))?;
|
||||
debug!("Sending SignedId with device_id={}", self.device_id);
|
||||
self.send_framed_arc(&writer, &signed_id_bytes).await?;
|
||||
}
|
||||
ConnectionMode::DirectIp => {
|
||||
// Standard RustDesk direct-IP clients do not perform the signed-ID handshake.
|
||||
// They expect password authentication to start immediately.
|
||||
let hash_msg = self.create_hash_message();
|
||||
let hash_bytes = hash_msg
|
||||
.write_to_bytes()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to encode Hash: {}", e))?;
|
||||
debug!("Sending password challenge for direct IP connection");
|
||||
self.send_framed_arc(&writer, &hash_bytes).await?;
|
||||
}
|
||||
}
|
||||
|
||||
// Channel for receiving video frames to send (bounded to provide backpressure)
|
||||
let (video_tx, mut video_rx) = mpsc::channel::<Bytes>(4);
|
||||
@@ -842,7 +871,11 @@ impl Connection {
|
||||
|
||||
// Sign the IdPk bytes with Ed25519
|
||||
// RustDesk's sign::sign() prepends the 64-byte signature to the message
|
||||
let signed_id_pk = self.signing_keypair.sign(&id_pk_bytes);
|
||||
let signed_id_pk = self
|
||||
.signing_keypair
|
||||
.as_ref()
|
||||
.expect("secure RustDesk connections require a signing keypair")
|
||||
.sign(&id_pk_bytes);
|
||||
|
||||
let mut signed_id = SignedId::new();
|
||||
signed_id.id = signed_id_pk.into();
|
||||
@@ -980,7 +1013,7 @@ impl Connection {
|
||||
/// Verify password
|
||||
fn verify_password(&self, provided: &[u8]) -> bool {
|
||||
// RustDesk password verification:
|
||||
// We send Hash { salt: device_id, challenge: "" } to client
|
||||
// We send a stable salt and a fresh per-connection challenge to the client.
|
||||
// The client calculates: SHA256(SHA256(password + salt) + challenge)
|
||||
// See create_hash_message() for the salt and challenge we use
|
||||
//
|
||||
@@ -993,9 +1026,11 @@ impl Connection {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The client calculates: SHA256(SHA256(password + salt) + challenge)
|
||||
// where salt is our device_id and challenge is empty
|
||||
let expected_hash = crypto::hash_password_double(&self.password, &self.device_id, "");
|
||||
let expected_hash = crypto::hash_password_double(
|
||||
&self.password,
|
||||
&self.password_salt,
|
||||
&self.password_challenge,
|
||||
);
|
||||
|
||||
// Try comparison with double hash
|
||||
if provided == expected_hash.as_slice() {
|
||||
@@ -1003,9 +1038,10 @@ impl Connection {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Also try single hash for compatibility
|
||||
let expected_hash_single = crypto::hash_password(&self.password, &self.device_id);
|
||||
if provided == expected_hash_single.as_slice() {
|
||||
// Keep the legacy single-hash fallback only inside the encrypted ID-service path.
|
||||
// It has no per-connection challenge and must not be accepted on direct IP access.
|
||||
let expected_hash_single = crypto::hash_password(&self.password, &self.password_salt);
|
||||
if self.mode == ConnectionMode::Secure && provided == expected_hash_single.as_slice() {
|
||||
debug!("Password verified with single hash");
|
||||
return true;
|
||||
}
|
||||
@@ -1116,11 +1152,9 @@ impl Connection {
|
||||
/// Create Hash message for password authentication
|
||||
/// The client will hash the password with the salt and send it back in LoginRequest
|
||||
fn create_hash_message(&self) -> HbbMessage {
|
||||
// Use device_id as salt for simplicity (RustDesk uses Config::get_salt())
|
||||
// The challenge field is not used for our password verification
|
||||
let mut hash = Hash::new();
|
||||
hash.salt = self.device_id.clone();
|
||||
hash.challenge = String::new();
|
||||
hash.salt = self.password_salt.clone();
|
||||
hash.challenge = self.password_challenge.clone();
|
||||
|
||||
let mut msg = HbbMessage::new();
|
||||
msg.union = Some(message::Union::Hash(hash));
|
||||
@@ -1397,6 +1431,10 @@ impl ConnectionManager {
|
||||
*self.video_manager.write() = Some(video_manager);
|
||||
}
|
||||
|
||||
pub fn update_config(&self, config: RustDeskConfig) {
|
||||
*self.config.write() = config;
|
||||
}
|
||||
|
||||
/// Set keypair
|
||||
pub fn set_keypair(&self, keypair: KeyPair) {
|
||||
*self.keypair.write() = Some(keypair);
|
||||
@@ -1431,6 +1469,25 @@ impl ConnectionManager {
|
||||
&self,
|
||||
stream: TcpStream,
|
||||
peer_addr: SocketAddr,
|
||||
) -> anyhow::Result<u32> {
|
||||
self.accept_connection_with_mode(stream, peer_addr, ConnectionMode::Secure)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn accept_direct_connection(
|
||||
&self,
|
||||
stream: TcpStream,
|
||||
peer_addr: SocketAddr,
|
||||
) -> anyhow::Result<u32> {
|
||||
self.accept_connection_with_mode(stream, peer_addr, ConnectionMode::DirectIp)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn accept_connection_with_mode(
|
||||
&self,
|
||||
stream: TcpStream,
|
||||
peer_addr: SocketAddr,
|
||||
mode: ConnectionMode,
|
||||
) -> anyhow::Result<u32> {
|
||||
let id = {
|
||||
let mut next = self.next_id.write();
|
||||
@@ -1440,12 +1497,22 @@ impl ConnectionManager {
|
||||
};
|
||||
|
||||
let config = self.config.read().clone();
|
||||
let signing_keypair = self.ensure_signing_keypair();
|
||||
let signing_keypair = match mode {
|
||||
ConnectionMode::Secure => Some(self.ensure_signing_keypair()),
|
||||
ConnectionMode::DirectIp => None,
|
||||
};
|
||||
let hid = self.hid.read().clone();
|
||||
let audio = self.audio.read().clone();
|
||||
let video_manager = self.video_manager.read().clone();
|
||||
let (mut conn, _rx) =
|
||||
Connection::new(id, &config, signing_keypair, hid, audio, video_manager);
|
||||
let (mut conn, _rx) = Connection::new(
|
||||
id,
|
||||
&config,
|
||||
mode,
|
||||
signing_keypair,
|
||||
hid,
|
||||
audio,
|
||||
video_manager,
|
||||
);
|
||||
|
||||
// Track connection state for external access
|
||||
let state = conn.state.clone();
|
||||
@@ -1781,3 +1848,100 @@ async fn run_audio_streaming(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn connection(mode: ConnectionMode) -> Connection {
|
||||
crypto::init().expect("crypto should initialize");
|
||||
let config = RustDeskConfig {
|
||||
device_id: "123456789".to_string(),
|
||||
device_password: "fixed-password".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let (connection, _rx) = Connection::new(
|
||||
1,
|
||||
&config,
|
||||
mode,
|
||||
(mode == ConnectionMode::Secure).then(SigningKeyPair::generate),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
connection
|
||||
}
|
||||
|
||||
async fn first_server_message(mode: ConnectionMode) -> HbbMessage {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("test listener should bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("listener should have an address");
|
||||
let client = tokio::spawn(async move {
|
||||
TcpStream::connect(address)
|
||||
.await
|
||||
.expect("client should connect")
|
||||
});
|
||||
let (server_stream, peer_addr) = listener.accept().await.expect("server should accept");
|
||||
let mut client_stream = client.await.expect("client task should finish");
|
||||
let mut server_connection = connection(mode);
|
||||
let server =
|
||||
tokio::spawn(
|
||||
async move { server_connection.handle_tcp(server_stream, peer_addr).await },
|
||||
);
|
||||
|
||||
let bytes = read_frame(&mut client_stream)
|
||||
.await
|
||||
.expect("client should receive the first frame");
|
||||
drop(client_stream);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(1), server).await;
|
||||
decode_message(&bytes).expect("first frame should contain a RustDesk message")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_ip_password_challenge_is_non_empty_and_verifiable() {
|
||||
let connection = connection(ConnectionMode::DirectIp);
|
||||
let message = connection.create_hash_message();
|
||||
let hash = match message.union {
|
||||
Some(message::Union::Hash(hash)) => hash,
|
||||
_ => panic!("expected Hash message"),
|
||||
};
|
||||
|
||||
assert_eq!(hash.salt, "123456789");
|
||||
assert!(!hash.challenge.is_empty());
|
||||
|
||||
let response = crypto::hash_password_double("fixed-password", &hash.salt, &hash.challenge);
|
||||
assert!(connection.verify_password(&response));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_ip_rejects_legacy_replayable_single_hash() {
|
||||
let direct = connection(ConnectionMode::DirectIp);
|
||||
let single_hash = crypto::hash_password("fixed-password", "123456789");
|
||||
assert!(!direct.verify_password(&single_hash));
|
||||
|
||||
let secure = connection(ConnectionMode::Secure);
|
||||
assert!(secure.verify_password(&single_hash));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn password_challenge_changes_for_each_connection() {
|
||||
let first = connection(ConnectionMode::DirectIp);
|
||||
let second = connection(ConnectionMode::DirectIp);
|
||||
assert_ne!(first.password_challenge, second.password_challenge);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_ip_connection_starts_with_password_hash() {
|
||||
let message = first_server_message(ConnectionMode::DirectIp).await;
|
||||
assert!(matches!(message.union, Some(message::Union::Hash(_))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secure_connection_starts_with_signed_id() {
|
||||
let message = first_server_message(ConnectionMode::Secure).await;
|
||||
assert!(matches!(message.union, Some(message::Union::SignedId(_))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ use crate::hid::HidController;
|
||||
use crate::utils::bind_tcp_listener;
|
||||
use crate::video::stream_manager::VideoStreamManager;
|
||||
|
||||
use self::config::RustDeskConfig;
|
||||
use self::config::{RustDeskConfig, RustDeskMode};
|
||||
use self::connection::ConnectionManager;
|
||||
use self::protocol::{make_local_addr, make_relay_response, make_request_relay};
|
||||
use self::rendezvous::{AddrMangle, RendezvousMediator, RendezvousStatus};
|
||||
@@ -53,8 +53,6 @@ impl std::fmt::Display for ServiceStatus {
|
||||
}
|
||||
}
|
||||
|
||||
const DIRECT_LISTEN_PORT: u16 = 21118;
|
||||
|
||||
pub struct RustDeskService {
|
||||
config: Arc<RwLock<RustDeskConfig>>,
|
||||
status: Arc<RwLock<ServiceStatus>>,
|
||||
@@ -78,6 +76,7 @@ impl RustDeskService {
|
||||
) -> Self {
|
||||
let (shutdown_tx, _) = broadcast::channel(1);
|
||||
let connection_manager = Arc::new(ConnectionManager::new(config.clone()));
|
||||
let direct_access_port = config.direct_access_port;
|
||||
|
||||
Self {
|
||||
config: Arc::new(RwLock::new(config)),
|
||||
@@ -85,7 +84,7 @@ impl RustDeskService {
|
||||
rendezvous: Arc::new(RwLock::new(None)),
|
||||
rendezvous_handle: Arc::new(RwLock::new(None)),
|
||||
tcp_listener_handle: Arc::new(RwLock::new(None)),
|
||||
listen_port: Arc::new(RwLock::new(DIRECT_LISTEN_PORT)),
|
||||
listen_port: Arc::new(RwLock::new(direct_access_port)),
|
||||
connection_manager,
|
||||
video_manager,
|
||||
hid,
|
||||
@@ -107,6 +106,7 @@ impl RustDeskService {
|
||||
}
|
||||
|
||||
pub fn update_config(&self, config: RustDeskConfig) {
|
||||
self.connection_manager.update_config(config.clone());
|
||||
*self.config.write() = config;
|
||||
}
|
||||
|
||||
@@ -126,6 +126,10 @@ impl RustDeskService {
|
||||
self.tcp_listener_handle.read().is_some()
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.status() == ServiceStatus::Running
|
||||
}
|
||||
|
||||
pub async fn start(&self) -> anyhow::Result<()> {
|
||||
let config = self.config.read().clone();
|
||||
|
||||
@@ -146,9 +150,8 @@ impl RustDeskService {
|
||||
|
||||
*self.status.write() = ServiceStatus::Starting;
|
||||
info!(
|
||||
"Starting RustDesk service with ID: {} -> {}",
|
||||
config.device_id,
|
||||
config.rendezvous_addr()
|
||||
"Starting RustDesk service in {:?} mode with ID: {}",
|
||||
config.mode, config.device_id,
|
||||
);
|
||||
|
||||
if let Err(e) = crypto::init() {
|
||||
@@ -157,6 +160,27 @@ impl RustDeskService {
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
self.connection_manager.set_hid(self.hid.clone());
|
||||
|
||||
self.connection_manager.set_audio(self.audio.clone());
|
||||
|
||||
self.connection_manager
|
||||
.set_video_manager(self.video_manager.clone());
|
||||
|
||||
if config.mode == RustDeskMode::DirectIp {
|
||||
let (tcp_handles, listen_port) = match self.start_tcp_listener_with_port().await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
*self.status.write() = ServiceStatus::Error(err.to_string());
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
*self.tcp_listener_handle.write() = Some(tcp_handles);
|
||||
*self.listen_port.write() = listen_port;
|
||||
*self.status.write() = ServiceStatus::Running;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mediator = Arc::new(RendezvousMediator::new(config.clone()));
|
||||
|
||||
let keypair = mediator.ensure_keypair();
|
||||
@@ -165,26 +189,8 @@ impl RustDeskService {
|
||||
let signing_keypair = mediator.ensure_signing_keypair();
|
||||
self.connection_manager.set_signing_keypair(signing_keypair);
|
||||
|
||||
self.connection_manager.set_hid(self.hid.clone());
|
||||
|
||||
self.connection_manager.set_audio(self.audio.clone());
|
||||
|
||||
self.connection_manager
|
||||
.set_video_manager(self.video_manager.clone());
|
||||
|
||||
*self.rendezvous.write() = Some(mediator.clone());
|
||||
|
||||
let (tcp_handles, listen_port) = match self.start_tcp_listener_with_port().await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
*self.status.write() = ServiceStatus::Error(err.to_string());
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
*self.tcp_listener_handle.write() = Some(tcp_handles);
|
||||
|
||||
mediator.set_listen_port(listen_port);
|
||||
|
||||
let connection_manager = self.connection_manager.clone();
|
||||
let service_config = self.config.clone();
|
||||
|
||||
@@ -299,16 +305,8 @@ impl RustDeskService {
|
||||
}
|
||||
|
||||
async fn start_tcp_listener_with_port(&self) -> anyhow::Result<(Vec<JoinHandle<()>>, u16)> {
|
||||
let (listeners, listen_port) = match self.bind_direct_listeners(DIRECT_LISTEN_PORT) {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Failed to bind RustDesk TCP on port {}: {}, falling back to random port",
|
||||
DIRECT_LISTEN_PORT, err
|
||||
);
|
||||
self.bind_direct_listeners(0)?
|
||||
}
|
||||
};
|
||||
let direct_access_port = self.config.read().direct_access_port;
|
||||
let (listeners, listen_port) = self.bind_direct_listeners(direct_access_port)?;
|
||||
|
||||
*self.listen_port.write() = listen_port;
|
||||
|
||||
@@ -330,7 +328,7 @@ impl RustDeskService {
|
||||
info!("Accepted direct connection from {}", peer_addr);
|
||||
let conn_mgr = conn_mgr.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = conn_mgr.accept_connection(stream, peer_addr).await {
|
||||
if let Err(e) = conn_mgr.accept_direct_connection(stream, peer_addr).await {
|
||||
error!("Failed to handle direct connection from {}: {}", peer_addr, e);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -53,7 +53,9 @@ async fn current_status(
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct RustDeskConfigResponse {
|
||||
pub enabled: bool,
|
||||
pub mode: crate::rustdesk::config::RustDeskMode,
|
||||
pub codec: crate::rustdesk::config::RustDeskCodec,
|
||||
pub direct_access_port: u16,
|
||||
pub rendezvous_server: String,
|
||||
pub relay_server: Option<String>,
|
||||
pub device_id: String,
|
||||
@@ -66,7 +68,9 @@ impl From<&RustDeskConfig> for RustDeskConfigResponse {
|
||||
fn from(config: &RustDeskConfig) -> Self {
|
||||
Self {
|
||||
enabled: config.enabled,
|
||||
mode: config.mode,
|
||||
codec: config.codec,
|
||||
direct_access_port: config.direct_access_port,
|
||||
rendezvous_server: config.rendezvous_server.clone(),
|
||||
relay_server: config.relay_server.clone(),
|
||||
device_id: config.device_id.clone(),
|
||||
@@ -117,28 +121,22 @@ pub async fn update_rustdesk_config(
|
||||
pub async fn regenerate_device_id(
|
||||
State(state): State<RemoteAccessApiState>,
|
||||
) -> Result<Json<RustDeskConfigResponse>> {
|
||||
state
|
||||
.config
|
||||
.update(|config| {
|
||||
config.rustdesk.device_id = RustDeskConfig::generate_device_id();
|
||||
})
|
||||
.await?;
|
||||
|
||||
let new_config = state.config.get().rustdesk.clone();
|
||||
let _apply_guard = try_apply_lock(&state.rustdesk_apply_lock, "rustdesk")?;
|
||||
let old_config = state.config.get().rustdesk.clone();
|
||||
let mut regenerated = old_config.clone();
|
||||
regenerated.device_id = RustDeskConfig::generate_device_id();
|
||||
let new_config = persist_and_apply(&state, old_config, regenerated).await?;
|
||||
Ok(Json(RustDeskConfigResponse::from(&new_config)))
|
||||
}
|
||||
|
||||
pub async fn regenerate_device_password(
|
||||
State(state): State<RemoteAccessApiState>,
|
||||
) -> Result<Json<RustDeskConfigResponse>> {
|
||||
state
|
||||
.config
|
||||
.update(|config| {
|
||||
config.rustdesk.device_password = RustDeskConfig::generate_password();
|
||||
})
|
||||
.await?;
|
||||
|
||||
let new_config = state.config.get().rustdesk.clone();
|
||||
let _apply_guard = try_apply_lock(&state.rustdesk_apply_lock, "rustdesk")?;
|
||||
let old_config = state.config.get().rustdesk.clone();
|
||||
let mut regenerated = old_config.clone();
|
||||
regenerated.device_password = RustDeskConfig::generate_password();
|
||||
let new_config = persist_and_apply(&state, old_config, regenerated).await?;
|
||||
Ok(Json(RustDeskConfigResponse::from(&new_config)))
|
||||
}
|
||||
|
||||
|
||||
@@ -899,7 +899,9 @@ fn validate_rustdesk_relay_key(key: &str) -> Result<(), AppError> {
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct RustDeskConfigUpdate {
|
||||
pub enabled: Option<bool>,
|
||||
pub mode: Option<crate::rustdesk::config::RustDeskMode>,
|
||||
pub codec: Option<crate::rustdesk::config::RustDeskCodec>,
|
||||
pub direct_access_port: Option<u16>,
|
||||
pub rendezvous_server: Option<String>,
|
||||
pub relay_server: Option<String>,
|
||||
pub relay_key: Option<String>,
|
||||
@@ -908,6 +910,11 @@ pub struct RustDeskConfigUpdate {
|
||||
|
||||
impl RustDeskConfigUpdate {
|
||||
pub fn validate(&self) -> crate::error::Result<()> {
|
||||
if self.direct_access_port == Some(0) {
|
||||
return Err(AppError::BadRequest(
|
||||
"RustDesk direct access port must be greater than 0".into(),
|
||||
));
|
||||
}
|
||||
// Validate rendezvous server format (should be host:port)
|
||||
if let Some(ref server) = self.rendezvous_server {
|
||||
if !server.is_empty() && !server.contains(':') {
|
||||
@@ -944,10 +951,24 @@ impl RustDeskConfigUpdate {
|
||||
}
|
||||
|
||||
pub fn validate_merged(&self, config: &RustDeskConfig) -> crate::error::Result<()> {
|
||||
if config.enabled && config.rendezvous_server.trim().is_empty() {
|
||||
return Err(AppError::BadRequest(
|
||||
"RustDesk ID server is required".into(),
|
||||
));
|
||||
if config.enabled {
|
||||
match config.mode {
|
||||
crate::rustdesk::config::RustDeskMode::Id
|
||||
if config.rendezvous_server.trim().is_empty() =>
|
||||
{
|
||||
return Err(AppError::BadRequest(
|
||||
"RustDesk ID server is required in ID service mode".into(),
|
||||
));
|
||||
}
|
||||
crate::rustdesk::config::RustDeskMode::DirectIp
|
||||
if config.direct_access_port == 0 =>
|
||||
{
|
||||
return Err(AppError::BadRequest(
|
||||
"RustDesk direct access port must be greater than 0".into(),
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -956,9 +977,15 @@ impl RustDeskConfigUpdate {
|
||||
if let Some(enabled) = self.enabled {
|
||||
config.enabled = enabled;
|
||||
}
|
||||
if let Some(mode) = self.mode {
|
||||
config.mode = mode;
|
||||
}
|
||||
if let Some(codec) = self.codec {
|
||||
config.codec = codec;
|
||||
}
|
||||
if let Some(port) = self.direct_access_port {
|
||||
config.direct_access_port = port;
|
||||
}
|
||||
if let Some(ref server) = self.rendezvous_server {
|
||||
config.rendezvous_server = server.clone();
|
||||
}
|
||||
@@ -1466,7 +1493,9 @@ mod tests {
|
||||
fn rustdesk_relay_key_accepts_hbbs_style_base64_32_bytes() {
|
||||
let update = RustDeskConfigUpdate {
|
||||
enabled: None,
|
||||
mode: None,
|
||||
codec: None,
|
||||
direct_access_port: None,
|
||||
rendezvous_server: None,
|
||||
relay_server: None,
|
||||
relay_key: Some("pLU0pEj2IZnNVKzrIO1pIdwGA3dOVJJLkFIYGOCGH1E=".to_string()),
|
||||
@@ -1481,7 +1510,9 @@ mod tests {
|
||||
let not_32 = "AAAAAAAAAAAAAAAAAAAAAA==".to_string();
|
||||
let update = RustDeskConfigUpdate {
|
||||
enabled: None,
|
||||
mode: None,
|
||||
codec: None,
|
||||
direct_access_port: None,
|
||||
rendezvous_server: None,
|
||||
relay_server: None,
|
||||
relay_key: Some(not_32),
|
||||
@@ -1490,6 +1521,49 @@ mod tests {
|
||||
assert!(update.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rustdesk_direct_ip_mode_does_not_require_id_server() {
|
||||
let mut config = RustDeskConfig::default();
|
||||
config.enabled = true;
|
||||
config.mode = crate::rustdesk::config::RustDeskMode::DirectIp;
|
||||
config.rendezvous_server.clear();
|
||||
|
||||
let update = RustDeskConfigUpdate {
|
||||
enabled: Some(true),
|
||||
mode: Some(crate::rustdesk::config::RustDeskMode::DirectIp),
|
||||
codec: None,
|
||||
direct_access_port: Some(21118),
|
||||
rendezvous_server: Some(String::new()),
|
||||
relay_server: None,
|
||||
relay_key: None,
|
||||
device_password: None,
|
||||
};
|
||||
|
||||
assert!(update.validate().is_ok());
|
||||
assert!(update.validate_merged(&config).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rustdesk_id_mode_requires_id_server_when_enabled() {
|
||||
let mut config = RustDeskConfig::default();
|
||||
config.enabled = true;
|
||||
config.mode = crate::rustdesk::config::RustDeskMode::Id;
|
||||
config.rendezvous_server.clear();
|
||||
|
||||
let update = RustDeskConfigUpdate {
|
||||
enabled: Some(true),
|
||||
mode: Some(crate::rustdesk::config::RustDeskMode::Id),
|
||||
codec: None,
|
||||
direct_access_port: None,
|
||||
rendezvous_server: Some(String::new()),
|
||||
relay_server: None,
|
||||
relay_key: None,
|
||||
device_password: None,
|
||||
};
|
||||
|
||||
assert!(update.validate_merged(&config).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6_bind_vnc_config_accepts_ipv6_literals() {
|
||||
for bind in ["::", "::1", "2001:db8::1"] {
|
||||
|
||||
Reference in New Issue
Block a user