temp commit

This commit is contained in:
chenbaiyu 2022-01-13 15:26:57 +08:00
parent 5b03e99404
commit 88f0f67ee3
4 changed files with 264 additions and 166 deletions

View File

@ -11,7 +11,6 @@ use std::{
sync::{Arc, Mutex, RwLock}, sync::{Arc, Mutex, RwLock},
time::SystemTime, time::SystemTime,
}; };
use std::borrow::Borrow;
pub const APP_NAME: &str = "RustDesk"; pub const APP_NAME: &str = "RustDesk";
pub const RENDEZVOUS_TIMEOUT: u64 = 12_000; pub const RENDEZVOUS_TIMEOUT: u64 = 12_000;
@ -163,28 +162,28 @@ pub struct PeerInfoSerde {
fn patch(path: PathBuf) -> PathBuf { fn patch(path: PathBuf) -> PathBuf {
if let Some(_tmp) = path.to_str() { if let Some(_tmp) = path.to_str() {
#[cfg(windows)] #[cfg(windows)]
return _tmp return _tmp
.replace( .replace(
"system32\\config\\systemprofile", "system32\\config\\systemprofile",
"ServiceProfiles\\LocalService", "ServiceProfiles\\LocalService",
) )
.into(); .into();
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
return _tmp.replace("Application Support", "Preferences").into(); return _tmp.replace("Application Support", "Preferences").into();
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
if _tmp == "/root" { if _tmp == "/root" {
if let Ok(output) = std::process::Command::new("whoami").output() { if let Ok(output) = std::process::Command::new("whoami").output() {
let user = String::from_utf8_lossy(&output.stdout) let user = String::from_utf8_lossy(&output.stdout)
.to_string() .to_string()
.trim() .trim()
.to_owned(); .to_owned();
if user != "root" { if user != "root" {
return format!("/home/{}", user).into(); return format!("/home/{}", user).into();
}
} }
} }
} }
}
} }
path path
} }
@ -276,7 +275,7 @@ impl Config {
pub fn get_home() -> PathBuf { pub fn get_home() -> PathBuf {
#[cfg(any(target_os = "android", target_os = "ios"))] #[cfg(any(target_os = "android", target_os = "ios"))]
return Self::path(""); return Self::path("");
if let Some(path) = dirs_next::home_dir() { if let Some(path) = dirs_next::home_dir() {
patch(path) patch(path)
} else if let Ok(path) = std::env::current_dir() { } else if let Ok(path) = std::env::current_dir() {
@ -288,15 +287,15 @@ impl Config {
pub fn path<P: AsRef<Path>>(p: P) -> PathBuf { pub fn path<P: AsRef<Path>>(p: P) -> PathBuf {
#[cfg(any(target_os = "android", target_os = "ios"))] #[cfg(any(target_os = "android", target_os = "ios"))]
{ {
let mut path: PathBuf = APP_DIR.read().unwrap().clone().into(); let mut path: PathBuf = APP_DIR.read().unwrap().clone().into();
path.push(p); path.push(p);
return path; return path;
} }
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let org = ""; let org = "";
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let org = ORG; let org = ORG;
// /var/root for root // /var/root for root
if let Some(project) = ProjectDirs::from("", org, APP_NAME) { if let Some(project) = ProjectDirs::from("", org, APP_NAME) {
let mut path = patch(project.config_dir().to_path_buf()); let mut path = patch(project.config_dir().to_path_buf());
@ -309,19 +308,19 @@ impl Config {
#[allow(unreachable_code)] #[allow(unreachable_code)]
pub fn log_path() -> PathBuf { pub fn log_path() -> PathBuf {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
if let Some(path) = dirs_next::home_dir().as_mut() { if let Some(path) = dirs_next::home_dir().as_mut() {
path.push(format!("Library/Logs/{}", APP_NAME)); path.push(format!("Library/Logs/{}", APP_NAME));
return path.clone(); return path.clone();
}
} }
}
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
let mut path = Self::get_home(); let mut path = Self::get_home();
path.push(format!(".local/share/logs/{}", APP_NAME)); path.push(format!(".local/share/logs/{}", APP_NAME));
std::fs::create_dir_all(&path).ok(); std::fs::create_dir_all(&path).ok();
return path; return path;
} }
if let Some(path) = Self::path("").parent() { if let Some(path) = Self::path("").parent() {
let mut path: PathBuf = path.into(); let mut path: PathBuf = path.into();
path.push("log"); path.push("log");
@ -332,21 +331,21 @@ impl Config {
pub fn ipc_path(postfix: &str) -> String { pub fn ipc_path(postfix: &str) -> String {
#[cfg(windows)] #[cfg(windows)]
{ {
// \\ServerName\pipe\PipeName // \\ServerName\pipe\PipeName
// where ServerName is either the name of a remote computer or a period, to specify the local computer. // where ServerName is either the name of a remote computer or a period, to specify the local computer.
// https://docs.microsoft.com/en-us/windows/win32/ipc/pipe-names // https://docs.microsoft.com/en-us/windows/win32/ipc/pipe-names
format!("\\\\.\\pipe\\{}\\query{}", APP_NAME, postfix) format!("\\\\.\\pipe\\{}\\query{}", APP_NAME, postfix)
} }
#[cfg(not(windows))] #[cfg(not(windows))]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
let mut path: PathBuf = format!("/tmp/{}", APP_NAME).into(); let mut path: PathBuf = format!("/tmp/{}", APP_NAME).into();
fs::create_dir(&path).ok(); fs::create_dir(&path).ok();
fs::set_permissions(&path, fs::Permissions::from_mode(0o0777)).ok(); fs::set_permissions(&path, fs::Permissions::from_mode(0o0777)).ok();
path.push(format!("ipc{}", postfix)); path.push(format!("ipc{}", postfix));
path.to_str().unwrap_or("").to_owned() path.to_str().unwrap_or("").to_owned()
} }
} }
pub fn icon_path() -> PathBuf { pub fn icon_path() -> PathBuf {
@ -460,7 +459,7 @@ impl Config {
fn get_auto_id() -> Option<String> { fn get_auto_id() -> Option<String> {
#[cfg(any(target_os = "android", target_os = "ios"))] #[cfg(any(target_os = "android", target_os = "ios"))]
return None; return None;
let mut id = 0u32; let mut id = 0u32;
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]
if let Ok(Some(ma)) = mac_address::get_mac_address() { if let Ok(Some(ma)) = mac_address::get_mac_address() {
@ -674,43 +673,91 @@ impl Config {
} }
} }
pub fn copy_and_reload_config_dir<P: AsRef<Path>>( pub fn sync_config_to_user<P: AsRef<Path>>(target_username: String, to_dir: P) -> bool {
target_username: String, let config1_root_file_path = Config::file_("");
from: P, let config1_filename = config1_root_file_path.file_name();
) -> Result<bool, fs_extra::error::Error> {
let to = Self::path("");
let to_parent = to.parent().unwrap();
let mut options = fs_extra::dir::CopyOptions::new(); let config2_root_file_path = Config::file_("2");
options.overwrite = true; let config2_filename = config2_root_file_path.file_name();
options.copy_inside = true;
let mut f = from.as_ref(); let config1_to_file_path = to_dir
.as_ref()
.join(PathBuf::from(&config1_filename.unwrap()));
let config2_to_file_path = to_dir
.as_ref()
.join(PathBuf::from(&config2_filename.unwrap()));
return match fs_extra::dir::copy(f, to_parent, &options) { log::info!(
Ok(count) => { "config1_root_path:{}",
if count > 0 { &config1_root_file_path.as_path().to_str().unwrap()
log::info!("{}",target_username); );
log::info!("{}",f.to_str().unwrap().to_string()); log::info!(
log::info!("{}",to.to_str().unwrap().to_string()); "config2_root_path:{}",
&config2_root_file_path.as_path().to_str().unwrap()
);
log::info!(
"config1_to_path:{}",
&config1_to_file_path.as_path().to_str().unwrap()
);
log::info!(
"config2_to_path:{}",
&config2_to_file_path.as_path().to_str().unwrap()
);
std::process::Command::new("chown") match std::fs::copy(&config1_root_file_path, &config1_to_file_path) {
.arg("-R") Err(e) => log::error!(
.arg(target_username) "copy config {} to user failed: {}",
.arg(to.to_str().unwrap().to_string()) config1_filename.unwrap().to_str().unwrap(),
.spawn(); e
),
_ => {}
}
CONFIG.write().unwrap().reload(); match std::fs::copy(&config2_root_file_path, &config2_to_file_path) {
CONFIG2.write().unwrap().reload(); Err(e) => log::error!(
"copy config {} to user failed: {}",
config2_filename.unwrap().to_str().unwrap(),
e
),
_ => {}
}
let success = std::process::Command::new("chown")
.arg(&target_username.to_string())
.arg(&config1_to_file_path.to_str().unwrap().to_string())
.arg(&config2_to_file_path.to_str().unwrap().to_string())
.spawn()
.is_ok();
if success {
CONFIG.write().unwrap().reload();
CONFIG2.write().unwrap().reload();
}
return success;
}
pub fn sync_config_to_root<P: AsRef<Path>>(from_file_path: P) -> bool {
if let Some(filename) = from_file_path.as_ref().file_name() {
let to = Config::path(filename);
return match std::fs::copy(from_file_path, &to) {
Ok(count) => {
if count > 0 {
return std::process::Command::new("chown")
.arg("root")
.arg(&to.to_str().unwrap().to_string())
.spawn()
.is_ok();
}
false
} }
Err(e) => {
Ok(count > 0) log::error!("sync_config_to_root failed: {}", e);
} false
Err(e) => { }
log::error!("config copy failed: {}", e); };
Err(e) }
} false
};
} }
} }

View File

@ -1,10 +1,20 @@
use hbb_common::{allow_err, bail, bytes, bytes_codec::BytesCodec, config::{self, Config}, futures::StreamExt as _, futures_util::sink::SinkExt, log, timeout, tokio, tokio::io::{AsyncRead, AsyncWrite}, tokio_util::codec::Framed, ResultType}; use hbb_common::log::info;
use hbb_common::{
allow_err, bail, bytes,
bytes_codec::BytesCodec,
config::{self, Config},
futures::StreamExt as _,
futures_util::sink::SinkExt,
log, timeout, tokio,
tokio::io::{AsyncRead, AsyncWrite},
tokio_util::codec::Framed,
ResultType,
};
use parity_tokio_ipc::{ use parity_tokio_ipc::{
Connection as Conn, ConnectionClient as ConnClient, Endpoint, Incoming, SecurityAttributes, Connection as Conn, ConnectionClient as ConnClient, Endpoint, Incoming, SecurityAttributes,
}; };
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::path::PathBuf;
#[cfg(not(windows))] #[cfg(not(windows))]
use std::{fs::File, io::prelude::*}; use std::{fs::File, io::prelude::*};
@ -83,17 +93,22 @@ pub enum Data {
Socks(Option<config::Socks5Server>), Socks(Option<config::Socks5Server>),
FS(FS), FS(FS),
Test, Test,
ConfigCopyReq { SyncConfigToRootReq {
target_username: String, from: String,
dir_path: String,
}, },
ConfigCopyResp(Option<bool>), SyncConfigToRootResp(bool),
SyncConfigToUserReq {
username: String,
to: String,
},
SyncConfigToUserResp(bool),
} }
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
pub async fn start(postfix: &str) -> ResultType<()> { pub async fn start(postfix: &str) -> ResultType<()> {
let mut incoming = new_listener(postfix).await?; let mut incoming = new_listener(postfix).await?;
loop { loop {
log::info!("begin loop");
if let Some(result) = incoming.next().await { if let Some(result) = incoming.next().await {
match result { match result {
Ok(stream) => { Ok(stream) => {
@ -101,13 +116,16 @@ pub async fn start(postfix: &str) -> ResultType<()> {
let postfix = postfix.to_owned(); let postfix = postfix.to_owned();
tokio::spawn(async move { tokio::spawn(async move {
loop { loop {
log::info!("begin loop");
match stream.next().await { match stream.next().await {
Err(err) => { Err(err) => {
log::trace!("ipc{} connection closed: {}", postfix, err); log::trace!("ipc{} connection closed: {}", postfix, err);
break; break;
} }
Ok(Some(data)) => { Ok(Some(data)) => {
log::info!("begin handle");
handle(data, &mut stream).await; handle(data, &mut stream).await;
log::info!("end handle");
} }
_ => {} _ => {}
} }
@ -125,7 +143,7 @@ pub async fn start(postfix: &str) -> ResultType<()> {
pub async fn new_listener(postfix: &str) -> ResultType<Incoming> { pub async fn new_listener(postfix: &str) -> ResultType<Incoming> {
let path = Config::ipc_path(postfix); let path = Config::ipc_path(postfix);
#[cfg(not(windows))] #[cfg(not(windows))]
check_pid(postfix).await; check_pid(postfix).await;
let mut endpoint = Endpoint::new(path.clone()); let mut endpoint = Endpoint::new(path.clone());
match SecurityAttributes::allow_everyone_create() { match SecurityAttributes::allow_everyone_create() {
Ok(attr) => endpoint.set_security_attributes(attr), Ok(attr) => endpoint.set_security_attributes(attr),
@ -135,11 +153,11 @@ pub async fn new_listener(postfix: &str) -> ResultType<Incoming> {
Ok(incoming) => { Ok(incoming) => {
log::info!("Started ipc{} server at path: {}", postfix, &path); log::info!("Started ipc{} server at path: {}", postfix, &path);
#[cfg(not(windows))] #[cfg(not(windows))]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o0777)).ok(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o0777)).ok();
write_pid(postfix); write_pid(postfix);
} }
Ok(incoming) Ok(incoming)
} }
Err(err) => { Err(err) => {
@ -248,22 +266,27 @@ async fn handle(data: Data, stream: &mut Connection) {
let t = Config::get_nat_type(); let t = Config::get_nat_type();
allow_err!(stream.send(&Data::NatType(Some(t))).await); allow_err!(stream.send(&Data::NatType(Some(t))).await);
} }
Data::ConfigCopyReq { target_username, dir_path } => { Data::SyncConfigToRootReq { from } => {
let from = PathBuf::from(dir_path); info!("begin SyncConfigToRootReq, {}", from);
if !from.exists() { allow_err!(
allow_err!(stream.send(&Data::ConfigCopyResp(None)).await); stream
return; .send(&Data::SyncConfigToRootResp(Config::sync_config_to_root(
} from
)))
match Config::copy_and_reload_config_dir(target_username, from) { .await
Ok(result) => { );
allow_err!(stream.send(&Data::ConfigCopyResp(Some(result))).await); info!("begin SyncConfigToRootReq end");
} }
Err(e) => { Data::SyncConfigToUserReq { username, to } => {
log::error!("copy_and_reload_config_dir failed: {:?}",e); info!("begin SyncConfigToUserReq,{},{}", username, to);
allow_err!(stream.send(&Data::ConfigCopyResp(Some(false))).await); allow_err!(
} stream
} .send(&Data::SyncConfigToUserResp(Config::sync_config_to_user(
username, to
)))
.await
);
info!("begin SyncConfigToUserReq end");
} }
_ => {} _ => {}
} }
@ -325,8 +348,8 @@ pub struct ConnectionTmpl<T> {
pub type Connection = ConnectionTmpl<Conn>; pub type Connection = ConnectionTmpl<Conn>;
impl<T> ConnectionTmpl<T> impl<T> ConnectionTmpl<T>
where where
T: AsyncRead + AsyncWrite + std::marker::Unpin, T: AsyncRead + AsyncWrite + std::marker::Unpin,
{ {
pub fn new(conn: T) -> Self { pub fn new(conn: T) -> Self {
Self { Self {

View File

@ -335,6 +335,7 @@ pub fn is_installed() -> bool {
} }
pub fn start_daemon(){ pub fn start_daemon(){
log::info!("{}",crate::username());
if let Err(err) = crate::ipc::start("_daemon") { if let Err(err) = crate::ipc::start("_daemon") {
log::error!("Failed to start ipc_daemon: {}", err); log::error!("Failed to start ipc_daemon: {}", err);
std::process::exit(-1); std::process::exit(-1);

View File

@ -14,7 +14,7 @@ use hbb_common::{
timeout, tokio, ResultType, Stream, timeout, tokio, ResultType, Stream,
}; };
use service::{GenericService, Service, ServiceTmpl, Subscriber}; use service::{GenericService, Service, ServiceTmpl, Subscriber};
use std::sync::mpsc::RecvError; use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use std::{ use std::{
collections::HashMap, collections::HashMap,
@ -22,7 +22,6 @@ use std::{
sync::{Arc, Mutex, RwLock, Weak}, sync::{Arc, Mutex, RwLock, Weak},
}; };
use hbb_common::log::info;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use notify::{watcher, RecursiveMode, Watcher}; use notify::{watcher, RecursiveMode, Watcher};
use parity_tokio_ipc::ConnectionClient; use parity_tokio_ipc::ConnectionClient;
@ -172,7 +171,7 @@ pub async fn create_relay_connection(
secure: bool, secure: bool,
) { ) {
if let Err(err) = if let Err(err) =
create_relay_connection_(server, relay_server, uuid.clone(), peer_addr, secure).await create_relay_connection_(server, relay_server, uuid.clone(), peer_addr, secure).await
{ {
log::error!( log::error!(
"Failed to create relay connection for {} with uuid {}: {}", "Failed to create relay connection for {} with uuid {}: {}",
@ -195,7 +194,7 @@ async fn create_relay_connection_(
Config::get_any_listen_addr(), Config::get_any_listen_addr(),
CONNECT_TIMEOUT, CONNECT_TIMEOUT,
) )
.await?; .await?;
let mut msg_out = RendezvousMessage::new(); let mut msg_out = RendezvousMessage::new();
msg_out.set_request_relay(RequestRelay { msg_out.set_request_relay(RequestRelay {
uuid, uuid,
@ -270,12 +269,14 @@ pub fn check_zombie() {
#[tokio::main] #[tokio::main]
pub async fn start_server(is_server: bool, _tray: bool) { pub async fn start_server(is_server: bool, _tray: bool) {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
log::info!("DISPLAY={:?}", std::env::var("DISPLAY")); log::info!("DISPLAY={:?}", std::env::var("DISPLAY"));
log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY")); log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY"));
} }
sync_and_watch_config_dir().await; tokio::spawn(async { sync_and_watch_config_dir().await });
log::info!("enter server");
if is_server { if is_server {
std::thread::spawn(move || { std::thread::spawn(move || {
@ -307,7 +308,7 @@ pub async fn start_server(is_server: bool, _tray: bool) {
} else { } else {
allow_err!(conn.send(&Data::ConfirmedKey(None)).await); allow_err!(conn.send(&Data::ConfirmedKey(None)).await);
if let Ok(Some(Data::ConfirmedKey(Some(pair)))) = if let Ok(Some(Data::ConfirmedKey(Some(pair)))) =
conn.next_timeout(1000).await conn.next_timeout(1000).await
{ {
Config::set_key_pair(pair); Config::set_key_pair(pair);
Config::set_key_confirmed(true); Config::set_key_confirmed(true);
@ -327,68 +328,94 @@ pub async fn start_server(is_server: bool, _tray: bool) {
} }
} }
async fn sync_and_watch_config_dir() -> ResultType<()> { async fn sync_and_watch_config_dir() {
let mut conn = crate::ipc::connect(1000, "_daemon").await?; if crate::username() == "root"{
return;
}
sync_config_dir(&mut conn, "/var/root/Library/Preferences/com.carriez.RustDesk/".to_string()).await?; match crate::ipc::connect(1000, "_daemon").await {
Ok(mut conn) => {
sync_config_to_user(&mut conn).await;
tokio::spawn(async move { log::info!(
log::info!( "watching config dir: {}",
"watching config dir: {}", Config::path("").to_str().unwrap().to_string()
Config::path("").to_str().unwrap().to_string() );
);
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap(); let mut watcher = watcher(tx, Duration::from_secs(2)).unwrap();
watcher watcher
.watch(Config::path("").as_path(), RecursiveMode::Recursive) .watch(Config::path("").as_path(), RecursiveMode::Recursive)
.unwrap(); .unwrap();
loop { loop {
let ev = rx.recv(); let ev = rx.recv();
match ev { match ev {
Ok(event) => match event { Ok(event) => match event {
notify::DebouncedEvent::Write(path) => { notify::DebouncedEvent::Write(path) => {
log::info!( log::info!(
"config file changed, call ipc_daemon to sync: {}", "config file changed, call ipc_daemon to sync: {}",
path.to_str().unwrap().to_string() path.to_str().unwrap().to_string()
); );
sync_config_dir(&mut conn, Config::path("").to_str().unwrap().to_string()).await; sync_config_to_root(&mut conn, path).await;
} log::info!("sync end");
x => { }
log::info!("another {:?}", x) x => {
} log::info!("another {:?}", x)
}, }
Err(e) => println!("watch error: {:?}", e), },
Err(e) => println!("watch error: {:?}", e),
}
} }
} }
}); Err(e) => {
log::info!("connect ipc_daemon failed, skip config sync");
Ok(()) return;
}
}
} }
async fn sync_config_dir(conn: &mut ConnectionTmpl<ConnectionClient>, path: String) -> ResultType<()> { async fn sync_config_to_user(conn: &mut ConnectionTmpl<ConnectionClient>) -> ResultType<()> {
allow_err!( allow_err!(
conn.send(&Data::ConfigCopyReq { conn.send(&Data::SyncConfigToUserReq {
target_username: crate::username(), username: crate::username(),
dir_path: path to: Config::path("").to_str().unwrap().to_string(),
}) })
.await .await
); );
if let Ok(Some(data)) = conn.next_timeout(1000).await {
if let Some(data) = conn.next_timeout(2000).await? {
match data { match data {
Data::ConfigCopyResp(result) => match result { Data::SyncConfigToUserResp(success) => {
Some(success) => { log::info!("copy and reload config dir success: {:?}", success);
if success { }
log::info!("copy and reload config dir success");
} else {
log::info!("copy config dir failed. may be first running");
}
}
None => {}
},
x => { x => {
log::info!("receive another {:?}",x) log::info!("receive another {:?}", x)
}
};
};
Ok(())
}
async fn sync_config_to_root(
conn: &mut ConnectionTmpl<ConnectionClient>,
from: PathBuf,
) -> ResultType<()> {
allow_err!(
conn.send(&Data::SyncConfigToRootReq {
from: from.to_str().unwrap().to_string()
})
.await
);
if let Some(data) = conn.next_timeout(2000).await? {
match data {
Data::SyncConfigToRootResp(success) => {
log::info!("copy config to root dir success: {:?}", success);
}
x => {
log::info!("receive another {:?}", x)
} }
}; };
}; };