Revert "temp commit"

This reverts commit 2e03ca19f6.
This commit is contained in:
chenbaiyu 2022-01-13 16:07:18 +08:00
parent 1995f9fa4e
commit e51e5ac4b1
9 changed files with 119 additions and 356 deletions

View file

@ -1,10 +1,19 @@
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::{
Connection as Conn, ConnectionClient as ConnClient, Endpoint, Incoming, SecurityAttributes,
};
use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[cfg(not(windows))]
use std::{fs::File, io::prelude::*};
@ -83,11 +92,6 @@ pub enum Data {
Socks(Option<config::Socks5Server>),
FS(FS),
Test,
ConfigCopyReq {
target_username: String,
dir_path: String,
},
ConfigCopyResp(Option<bool>),
}
#[tokio::main(flavor = "current_thread")]
@ -125,7 +129,7 @@ pub async fn start(postfix: &str) -> ResultType<()> {
pub async fn new_listener(postfix: &str) -> ResultType<Incoming> {
let path = Config::ipc_path(postfix);
#[cfg(not(windows))]
check_pid(postfix).await;
check_pid(postfix).await;
let mut endpoint = Endpoint::new(path.clone());
match SecurityAttributes::allow_everyone_create() {
Ok(attr) => endpoint.set_security_attributes(attr),
@ -135,11 +139,11 @@ pub async fn new_listener(postfix: &str) -> ResultType<Incoming> {
Ok(incoming) => {
log::info!("Started ipc{} server at path: {}", postfix, &path);
#[cfg(not(windows))]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o0777)).ok();
write_pid(postfix);
}
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o0777)).ok();
write_pid(postfix);
}
Ok(incoming)
}
Err(err) => {
@ -248,23 +252,6 @@ async fn handle(data: Data, stream: &mut Connection) {
let t = Config::get_nat_type();
allow_err!(stream.send(&Data::NatType(Some(t))).await);
}
Data::ConfigCopyReq { target_username, dir_path } => {
let from = PathBuf::from(dir_path);
if !from.exists() {
allow_err!(stream.send(&Data::ConfigCopyResp(None)).await);
return;
}
match Config::copy_and_reload_config_dir(target_username, from) {
Ok(result) => {
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);
}
}
}
_ => {}
}
}
@ -325,8 +312,8 @@ pub struct ConnectionTmpl<T> {
pub type Connection = ConnectionTmpl<Conn>;
impl<T> ConnectionTmpl<T>
where
T: AsyncRead + AsyncWrite + std::marker::Unpin,
where
T: AsyncRead + AsyncWrite + std::marker::Unpin,
{
pub fn new(conn: T) -> Self {
Self {

View file

@ -27,4 +27,4 @@ use common::*;
pub mod cli;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
mod port_forward;
mod lang;
mod lang;

View file

@ -10,7 +10,7 @@ fn main() {
common::test_rendezvous_server();
common::test_nat_type();
#[cfg(target_os = "android")]
crate::common::check_software_update();
crate::common::check_software_update();
mobile::Session::start("");
}
@ -29,53 +29,53 @@ fn main() {
return;
}
#[cfg(not(feature = "inline"))]
{
use hbb_common::env_logger::*;
init_from_env(Env::default().filter_or(DEFAULT_FILTER_ENV, "info"));
}
{
use hbb_common::env_logger::*;
init_from_env(Env::default().filter_or(DEFAULT_FILTER_ENV, "info"));
}
#[cfg(feature = "inline")]
{
let mut path = hbb_common::config::Config::log_path();
if args.len() > 0 && args[0].starts_with("--") {
let name = args[0].replace("--", "");
if !name.is_empty() {
path.push(name);
}
{
let mut path = hbb_common::config::Config::log_path();
if args.len() > 0 && args[0].starts_with("--") {
let name = args[0].replace("--", "");
if !name.is_empty() {
path.push(name);
}
use flexi_logger::*;
Logger::try_with_env_or_str("debug")
.map(|x| {
x.log_to_file(FileSpec::default().directory(path))
.format(opt_format)
.rotate(
Criterion::Age(Age::Day),
Naming::Timestamps,
Cleanup::KeepLogFiles(6),
)
.start()
.ok();
})
.ok();
}
use flexi_logger::*;
Logger::try_with_env_or_str("debug")
.map(|x| {
x.log_to_file(FileSpec::default().directory(path))
.format(opt_format)
.rotate(
Criterion::Age(Age::Day),
Naming::Timestamps,
Cleanup::KeepLogFiles(6),
)
.start()
.ok();
})
.ok();
}
if args.is_empty() {
std::thread::spawn(move || start_server(false, false));
} else {
#[cfg(windows)]
{
if args[0] == "--uninstall" {
if let Err(err) = platform::uninstall_me() {
log::error!("Failed to uninstall: {}", err);
}
return;
} else if args[0] == "--update" {
hbb_common::allow_err!(platform::update_me());
return;
} else if args[0] == "--reinstall" {
hbb_common::allow_err!(platform::uninstall_me());
hbb_common::allow_err!(platform::install_me("desktopicon startmenu",));
return;
{
if args[0] == "--uninstall" {
if let Err(err) = platform::uninstall_me() {
log::error!("Failed to uninstall: {}", err);
}
return;
} else if args[0] == "--update" {
hbb_common::allow_err!(platform::update_me());
return;
} else if args[0] == "--reinstall" {
hbb_common::allow_err!(platform::uninstall_me());
hbb_common::allow_err!(platform::install_me("desktopicon startmenu",));
return;
}
}
if args[0] == "--remove" {
if args.len() == 2 {
// sleep a while so that process of removed exe exit
@ -101,10 +101,6 @@ fn main() {
ipc::set_password(args[1].to_owned()).unwrap();
}
return;
} else if cfg!(target_os = "macos") && args[0] == "--daemon" {
log::info!("start --daemon");
crate::platform::start_daemon();
return;
}
}
ui::start(&mut args[..]);

View file

@ -333,10 +333,3 @@ pub fn block_input(_v: bool) {
pub fn is_installed() -> bool {
true
}
pub fn start_daemon(){
if let Err(err) = crate::ipc::start("_daemon") {
log::error!("Failed to start ipc_daemon: {}", err);
std::process::exit(-1);
}
}

View file

@ -1,4 +1,4 @@
use crate::ipc::{ConnectionTmpl, Data};
use crate::ipc::Data;
use connection::{ConnInner, Connection};
use hbb_common::{
allow_err,
@ -9,24 +9,18 @@ use hbb_common::{
message_proto::*,
protobuf::{Message as _, ProtobufEnum},
rendezvous_proto::*,
sleep, socket_client,
sleep,
sodiumoxide::crypto::{box_, secretbox, sign},
timeout, tokio, ResultType, Stream,
socket_client,
};
use service::{GenericService, Service, ServiceTmpl, Subscriber};
use std::sync::mpsc::RecvError;
use std::time::Duration;
use std::{
collections::HashMap,
net::SocketAddr,
sync::{Arc, Mutex, RwLock, Weak},
};
use hbb_common::log::info;
#[cfg(target_os = "macos")]
use notify::{watcher, RecursiveMode, Watcher};
use parity_tokio_ipc::ConnectionClient;
mod audio_service;
mod clipboard_service;
mod connection;
@ -172,7 +166,7 @@ pub async fn create_relay_connection(
secure: bool,
) {
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!(
"Failed to create relay connection for {} with uuid {}: {}",
@ -195,7 +189,7 @@ async fn create_relay_connection_(
Config::get_any_listen_addr(),
CONNECT_TIMEOUT,
)
.await?;
.await?;
let mut msg_out = RendezvousMessage::new();
msg_out.set_request_relay(RequestRelay {
uuid,
@ -270,13 +264,10 @@ pub fn check_zombie() {
#[tokio::main]
pub async fn start_server(is_server: bool, _tray: bool) {
#[cfg(target_os = "linux")]
{
log::info!("DISPLAY={:?}", std::env::var("DISPLAY"));
log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY"));
}
sync_and_watch_config_dir().await;
{
log::info!("DISPLAY={:?}", std::env::var("DISPLAY"));
log::info!("XAUTHORITY={:?}", std::env::var("XAUTHORITY"));
}
if is_server {
std::thread::spawn(move || {
if let Err(err) = crate::ipc::start("") {
@ -307,7 +298,7 @@ pub async fn start_server(is_server: bool, _tray: bool) {
} else {
allow_err!(conn.send(&Data::ConfirmedKey(None)).await);
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_confirmed(true);
@ -326,72 +317,3 @@ pub async fn start_server(is_server: bool, _tray: bool) {
}
}
}
async fn sync_and_watch_config_dir() -> ResultType<()> {
let mut conn = crate::ipc::connect(1000, "_daemon").await?;
sync_config_dir(&mut conn, "/var/root/Library/Preferences/com.carriez.RustDesk/".to_string()).await?;
tokio::spawn(async move {
log::info!(
"watching config dir: {}",
Config::path("").to_str().unwrap().to_string()
);
let (tx, rx) = std::sync::mpsc::channel();
let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap();
watcher
.watch(Config::path("").as_path(), RecursiveMode::Recursive)
.unwrap();
loop {
let ev = rx.recv();
match ev {
Ok(event) => match event {
notify::DebouncedEvent::Write(path) => {
log::info!(
"config file changed, call ipc_daemon to sync: {}",
path.to_str().unwrap().to_string()
);
sync_config_dir(&mut conn, Config::path("").to_str().unwrap().to_string()).await;
}
x => {
log::info!("another {:?}", x)
}
},
Err(e) => println!("watch error: {:?}", e),
}
}
});
Ok(())
}
async fn sync_config_dir(conn: &mut ConnectionTmpl<ConnectionClient>, path: String) -> ResultType<()> {
allow_err!(
conn.send(&Data::ConfigCopyReq {
target_username: crate::username(),
dir_path: path
})
.await
);
if let Ok(Some(data)) = conn.next_timeout(1000).await {
match data {
Data::ConfigCopyResp(result) => match result {
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 => {
log::info!("receive another {:?}",x)
}
};
};
Ok(())
}