refactoring conn audit, add session_id (both session_id and conn_id on

sever side), use session_id instead of conn_id for client id, and remove
conn_id in protobuf
This commit is contained in:
rustdesk 2023-07-01 16:21:36 +08:00
parent a33c94a377
commit 8ab2a79fa2
9 changed files with 27 additions and 24 deletions

View File

@ -97,7 +97,6 @@ message PeerInfo {
int32 current_display = 5; int32 current_display = 5;
bool sas_enabled = 6; bool sas_enabled = 6;
string version = 7; string version = 7;
int32 conn_id = 8;
Features features = 9; Features features = 9;
SupportedEncoding encoding = 10; SupportedEncoding encoding = 10;
SupportedResolutions resolutions = 11; SupportedResolutions resolutions = 11;

View File

@ -1073,9 +1073,8 @@ pub struct LoginConfigHandler {
config: PeerConfig, config: PeerConfig,
pub port_forward: (String, i32), pub port_forward: (String, i32),
pub version: i64, pub version: i64,
pub conn_id: i32,
features: Option<Features>, features: Option<Features>,
session_id: u64, pub session_id: u64, // used for local <-> server communication
pub supported_encoding: SupportedEncoding, pub supported_encoding: SupportedEncoding,
pub restarting_remote_device: bool, pub restarting_remote_device: bool,
pub force_relay: bool, pub force_relay: bool,
@ -1123,7 +1122,11 @@ impl LoginConfigHandler {
let config = self.load_config(); let config = self.load_config();
self.remember = !config.password.is_empty(); self.remember = !config.password.is_empty();
self.config = config; self.config = config;
self.session_id = rand::random(); let mut sid = rand::random();
if sid == 0 { // you won the lottery
sid = 1;
}
self.session_id = sid;
self.supported_encoding = Default::default(); self.supported_encoding = Default::default();
self.restarting_remote_device = false; self.restarting_remote_device = false;
self.force_relay = !self.get_option("force-always-relay").is_empty() || force_relay; self.force_relay = !self.get_option("force-always-relay").is_empty() || force_relay;
@ -1669,7 +1672,6 @@ impl LoginConfigHandler {
config.keyboard_mode = KeyboardMode::Legacy.to_string(); config.keyboard_mode = KeyboardMode::Legacy.to_string();
} }
} }
self.conn_id = pi.conn_id;
// no matter if change, for update file time // no matter if change, for update file time
self.save_config(config); self.save_config(config);
self.supported_encoding = pi.encoding.clone().unwrap_or_default(); self.supported_encoding = pi.encoding.clone().unwrap_or_default();

View File

@ -1415,11 +1415,8 @@ impl<T: InvokeUiSession> Remote<T> {
} }
} }
} }
Some(message::Union::PeerInfo(pi)) => match pi.conn_id { Some(message::Union::PeerInfo(pi)) => {
crate::SYNC_PEER_INFO_DISPLAYS => { self.handler.set_displays(&pi.displays);
self.handler.set_displays(&pi.displays);
}
_ => {}
}, },
_ => {} _ => {}
} }

View File

@ -39,8 +39,6 @@ pub type NotifyMessageBox = fn(String, String, String, String) -> dyn Future<Out
pub const CLIPBOARD_NAME: &'static str = "clipboard"; pub const CLIPBOARD_NAME: &'static str = "clipboard";
pub const CLIPBOARD_INTERVAL: u64 = 333; pub const CLIPBOARD_INTERVAL: u64 = 333;
pub const SYNC_PEER_INFO_DISPLAYS: i32 = 1;
#[cfg(all(target_os = "macos", feature = "flutter_texture_render"))] #[cfg(all(target_os = "macos", feature = "flutter_texture_render"))]
// https://developer.apple.com/forums/thread/712709 // https://developer.apple.com/forums/thread/712709
// Memory alignment should be multiple of 64. // Memory alignment should be multiple of 64.

View File

@ -90,7 +90,7 @@ pub fn new() -> ServerPtr {
let mut server = Server { let mut server = Server {
connections: HashMap::new(), connections: HashMap::new(),
services: HashMap::new(), services: HashMap::new(),
id_count: 0, id_count: hbb_common::rand::random::<i32>() % 1000,
}; };
server.add_service(Box::new(audio_service::new())); server.add_service(Box::new(audio_service::new()));
server.add_service(Box::new(video_service::new())); server.add_service(Box::new(video_service::new()));

View File

@ -192,6 +192,7 @@ pub struct Connection {
#[cfg(all(target_os = "linux", feature = "linux_headless"))] #[cfg(all(target_os = "linux", feature = "linux_headless"))]
#[cfg(not(any(feature = "flatpak", feature = "appimage")))] #[cfg(not(any(feature = "flatpak", feature = "appimage")))]
tx_desktop_ready: mpsc::Sender<()>, tx_desktop_ready: mpsc::Sender<()>,
closed: bool,
} }
impl ConnInner { impl ConnInner {
@ -320,8 +321,10 @@ impl Connection {
#[cfg(all(target_os = "linux", feature = "linux_headless"))] #[cfg(all(target_os = "linux", feature = "linux_headless"))]
#[cfg(not(any(feature = "flatpak", feature = "appimage")))] #[cfg(not(any(feature = "flatpak", feature = "appimage")))]
tx_desktop_ready: _tx_desktop_ready, tx_desktop_ready: _tx_desktop_ready,
closed: false,
}; };
if !conn.on_open(addr).await { if !conn.on_open(addr).await {
conn.closed = true;
// sleep to ensure msg got received. // sleep to ensure msg got received.
sleep(1.).await; sleep(1.).await;
return; return;
@ -563,7 +566,7 @@ impl Connection {
match &m.union { match &m.union {
Some(misc::Union::StopService(_)) => { Some(misc::Union::StopService(_)) => {
conn.send_close_reason_no_retry("").await; conn.send_close_reason_no_retry("").await;
conn.on_close("stop service", true).await; conn.on_close("stop service", false).await;
break; break;
} }
_ => {}, _ => {},
@ -634,6 +637,7 @@ impl Connection {
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]
try_stop_record_cursor_pos(); try_stop_record_cursor_pos();
} }
conn.on_close("End", true).await;
log::info!("#{} connection loop exited", id); log::info!("#{} connection loop exited", id);
} }
@ -867,6 +871,7 @@ impl Connection {
v["id"] = json!(Config::get_id()); v["id"] = json!(Config::get_id());
v["uuid"] = json!(crate::encode64(hbb_common::get_uuid())); v["uuid"] = json!(crate::encode64(hbb_common::get_uuid()));
v["conn_id"] = json!(self.inner.id); v["conn_id"] = json!(self.inner.id);
v["session_id"] = json!(self.lr.session_id);
tokio::spawn(async move { tokio::spawn(async move {
allow_err!(Self::post_audit_async(url, v).await); allow_err!(Self::post_audit_async(url, v).await);
}); });
@ -948,7 +953,6 @@ impl Connection {
let mut res = LoginResponse::new(); let mut res = LoginResponse::new();
let mut pi = PeerInfo { let mut pi = PeerInfo {
username: username.clone(), username: username.clone(),
conn_id: self.inner.id,
version: VERSION.to_owned(), version: VERSION.to_owned(),
..Default::default() ..Default::default()
}; };
@ -1228,6 +1232,7 @@ impl Connection {
.lock() .lock()
.unwrap() .unwrap()
.retain(|_, s| s.last_recv_time.lock().unwrap().elapsed() < SESSION_TIMEOUT); .retain(|_, s| s.last_recv_time.lock().unwrap().elapsed() < SESSION_TIMEOUT);
// last_recv_time is a mutex variable shared with connection, can be updated lively.
if let Some(session) = session { if let Some(session) = session {
if session.name == self.lr.my_name if session.name == self.lr.my_name
&& session.session_id == self.lr.session_id && session.session_id == self.lr.session_id
@ -2179,6 +2184,10 @@ impl Connection {
} }
async fn on_close(&mut self, reason: &str, lock: bool) { async fn on_close(&mut self, reason: &str, lock: bool) {
if self.closed {
return;
}
self.closed = true;
log::info!("#{} Connection closed: {}", self.inner.id(), reason); log::info!("#{} Connection closed: {}", self.inner.id(), reason);
if lock && self.lock_after_session_end && self.keyboard { if lock && self.lock_after_session_end && self.keyboard {
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]

View File

@ -484,7 +484,6 @@ fn check_get_displays_changed_msg() -> Option<Message> {
let displays = check_displays_new()?; let displays = check_displays_new()?;
let (current, displays) = get_displays_2(&displays); let (current, displays) = get_displays_2(&displays);
let mut pi = PeerInfo { let mut pi = PeerInfo {
conn_id: crate::SYNC_PEER_INFO_DISPLAYS,
..Default::default() ..Default::default()
}; };
pi.displays = displays.clone(); pi.displays = displays.clone();

View File

@ -61,7 +61,7 @@ pub fn make_tray() -> hbb_common::ResultType<()> {
let mut docker_hiden = false; let mut docker_hiden = false;
let open_func = move || { let open_func = move || {
#[cfg(not(feature = "flutter"))] if cfg!(not(feature = "flutter"))
{ {
crate::run_me::<&str>(vec![]).ok(); crate::run_me::<&str>(vec![]).ok();
return; return;

View File

@ -49,7 +49,7 @@ const CHANGE_RESOLUTION_VALID_TIMEOUT_SECS: u64 = 15;
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct Session<T: InvokeUiSession> { pub struct Session<T: InvokeUiSession> {
pub session_id: SessionID, pub session_id: SessionID, // different from the one in LoginConfigHandler, used for flutter UI message pass
pub id: String, // peer id pub id: String, // peer id
pub password: String, pub password: String,
pub args: Vec<String>, pub args: Vec<String>,
@ -312,8 +312,7 @@ impl<T: InvokeUiSession> Session<T> {
} }
pub fn get_audit_server(&self, typ: String) -> String { pub fn get_audit_server(&self, typ: String) -> String {
if self.lc.read().unwrap().conn_id <= 0 if LocalConfig::get_option("access_token").is_empty()
|| LocalConfig::get_option("access_token").is_empty()
{ {
return "".to_owned(); return "".to_owned();
} }
@ -327,9 +326,9 @@ impl<T: InvokeUiSession> Session<T> {
pub fn send_note(&self, note: String) { pub fn send_note(&self, note: String) {
let url = self.get_audit_server("conn".to_string()); let url = self.get_audit_server("conn".to_string());
let id = self.id.clone(); let id = self.id.clone();
let conn_id = self.lc.read().unwrap().conn_id; let session_id = self.lc.read().unwrap().session_id;
std::thread::spawn(move || { std::thread::spawn(move || {
send_note(url, id, conn_id, note); send_note(url, id, session_id, note);
}); });
} }
@ -1347,7 +1346,7 @@ async fn start_one_port_forward<T: InvokeUiSession>(
} }
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
async fn send_note(url: String, id: String, conn_id: i32, note: String) { async fn send_note(url: String, id: String, sid: u64, note: String) {
let body = serde_json::json!({ "id": id, "conn_id": conn_id, "note": note }); let body = serde_json::json!({ "id": id, "session_id": sid, "note": note });
allow_err!(crate::post_request(url, body.to_string(), "").await); allow_err!(crate::post_request(url, body.to_string(), "").await);
} }