Revert "temp commit"

This reverts commit 88f0f67ee321429c94f3fc2419edd537382917de.
This commit is contained in:
chenbaiyu 2022-01-13 16:06:51 +08:00
parent 88f0f67ee3
commit 1995f9fa4e
4 changed files with 174 additions and 272 deletions

View File

@ -11,6 +11,7 @@ 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;
@ -673,92 +674,44 @@ impl Config {
} }
} }
pub fn sync_config_to_user<P: AsRef<Path>>(target_username: String, to_dir: P) -> bool { pub fn copy_and_reload_config_dir<P: AsRef<Path>>(
let config1_root_file_path = Config::file_(""); target_username: String,
let config1_filename = config1_root_file_path.file_name(); from: P,
) -> Result<bool, fs_extra::error::Error> {
let to = Self::path("");
let to_parent = to.parent().unwrap();
let config2_root_file_path = Config::file_("2"); let mut options = fs_extra::dir::CopyOptions::new();
let config2_filename = config2_root_file_path.file_name(); options.overwrite = true;
options.copy_inside = true;
let config1_to_file_path = to_dir let mut f = from.as_ref();
.as_ref()
.join(PathBuf::from(&config1_filename.unwrap()));
let config2_to_file_path = to_dir
.as_ref()
.join(PathBuf::from(&config2_filename.unwrap()));
log::info!( return match fs_extra::dir::copy(f, to_parent, &options) {
"config1_root_path:{}", Ok(count) => {
&config1_root_file_path.as_path().to_str().unwrap() if count > 0 {
); log::info!("{}",target_username);
log::info!( log::info!("{}",f.to_str().unwrap().to_string());
"config2_root_path:{}", log::info!("{}",to.to_str().unwrap().to_string());
&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()
);
match std::fs::copy(&config1_root_file_path, &config1_to_file_path) { std::process::Command::new("chown")
Err(e) => log::error!( .arg("-R")
"copy config {} to user failed: {}", .arg(target_username)
config1_filename.unwrap().to_str().unwrap(), .arg(to.to_str().unwrap().to_string())
e .spawn();
),
_ => {}
}
match std::fs::copy(&config2_root_file_path, &config2_to_file_path) {
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(); CONFIG.write().unwrap().reload();
CONFIG2.write().unwrap().reload(); CONFIG2.write().unwrap().reload();
} }
return success; Ok(count > 0)
}
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) => { Err(e) => {
log::error!("sync_config_to_root failed: {}", e); log::error!("config copy failed: {}", e);
false Err(e)
} }
}; };
} }
false
}
} }
const PEERS: &str = "peers"; const PEERS: &str = "peers";

View File

@ -1,20 +1,10 @@
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 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::*};
@ -93,22 +83,17 @@ pub enum Data {
Socks(Option<config::Socks5Server>), Socks(Option<config::Socks5Server>),
FS(FS), FS(FS),
Test, Test,
SyncConfigToRootReq { ConfigCopyReq {
from: String, target_username: String,
dir_path: String,
}, },
SyncConfigToRootResp(bool), ConfigCopyResp(Option<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) => {
@ -116,16 +101,13 @@ 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");
} }
_ => {} _ => {}
} }
@ -266,27 +248,22 @@ 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::SyncConfigToRootReq { from } => { Data::ConfigCopyReq { target_username, dir_path } => {
info!("begin SyncConfigToRootReq, {}", from); let from = PathBuf::from(dir_path);
allow_err!( if !from.exists() {
stream allow_err!(stream.send(&Data::ConfigCopyResp(None)).await);
.send(&Data::SyncConfigToRootResp(Config::sync_config_to_root( return;
from }
)))
.await match Config::copy_and_reload_config_dir(target_username, from) {
); Ok(result) => {
info!("begin SyncConfigToRootReq end"); allow_err!(stream.send(&Data::ConfigCopyResp(Some(result))).await);
}
Err(e) => {
log::error!("copy_and_reload_config_dir failed: {:?}",e);
allow_err!(stream.send(&Data::ConfigCopyResp(Some(false))).await);
}
} }
Data::SyncConfigToUserReq { username, to } => {
info!("begin SyncConfigToUserReq,{},{}", username, to);
allow_err!(
stream
.send(&Data::SyncConfigToUserResp(Config::sync_config_to_user(
username, to
)))
.await
);
info!("begin SyncConfigToUserReq end");
} }
_ => {} _ => {}
} }
@ -348,7 +325,7 @@ 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 {

View File

@ -335,7 +335,6 @@ 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::path::PathBuf; use std::sync::mpsc::RecvError;
use std::time::Duration; use std::time::Duration;
use std::{ use std::{
collections::HashMap, collections::HashMap,
@ -22,6 +22,7 @@ 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;
@ -274,9 +275,7 @@ pub async fn start_server(is_server: bool, _tray: bool) {
log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY")); log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY"));
} }
tokio::spawn(async { sync_and_watch_config_dir().await }); sync_and_watch_config_dir().await;
log::info!("enter server");
if is_server { if is_server {
std::thread::spawn(move || { std::thread::spawn(move || {
@ -328,22 +327,19 @@ pub async fn start_server(is_server: bool, _tray: bool) {
} }
} }
async fn sync_and_watch_config_dir() { async fn sync_and_watch_config_dir() -> ResultType<()> {
if crate::username() == "root"{ let mut conn = crate::ipc::connect(1000, "_daemon").await?;
return;
}
match crate::ipc::connect(1000, "_daemon").await { sync_config_dir(&mut conn, "/var/root/Library/Preferences/com.carriez.RustDesk/".to_string()).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(2)).unwrap(); let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
watcher watcher
.watch(Config::path("").as_path(), RecursiveMode::Recursive) .watch(Config::path("").as_path(), RecursiveMode::Recursive)
.unwrap(); .unwrap();
@ -357,8 +353,7 @@ async fn sync_and_watch_config_dir() {
"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_to_root(&mut conn, path).await; sync_config_dir(&mut conn, Config::path("").to_str().unwrap().to_string()).await;
log::info!("sync end");
} }
x => { x => {
log::info!("another {:?}", x) log::info!("another {:?}", x)
@ -367,55 +362,33 @@ async fn sync_and_watch_config_dir() {
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_to_user(conn: &mut ConnectionTmpl<ConnectionClient>) -> ResultType<()> { async fn sync_config_dir(conn: &mut ConnectionTmpl<ConnectionClient>, path: String) -> ResultType<()> {
allow_err!( allow_err!(
conn.send(&Data::SyncConfigToUserReq { conn.send(&Data::ConfigCopyReq {
username: crate::username(), target_username: crate::username(),
to: Config::path("").to_str().unwrap().to_string(), dir_path: path
}) })
.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::SyncConfigToUserResp(success) => { Data::ConfigCopyResp(result) => match result {
log::info!("copy and reload config dir success: {:?}", success); Some(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)
} }
}; };
}; };