better control of clipboard file transfer

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou 2022-02-22 22:26:22 +08:00
parent 8834251eec
commit 2f6b457b3f
7 changed files with 183 additions and 16 deletions

View File

@ -192,6 +192,8 @@ extern "C"
typedef UINT (*pcCliprdrServerFileContentsResponse)(
CliprdrClientContext *context, const CLIPRDR_FILE_CONTENTS_RESPONSE *fileContentsResponse);
typedef BOOL (*pcCheckEnabled)(UINT32 server_conn_id, UINT32 remote_conn_id);
// TODO: hide more members of clipboard context
struct _cliprdr_client_context
{
@ -199,6 +201,7 @@ extern "C"
BOOL enableFiles;
BOOL enableOthers;
pcCheckEnabled CheckEnabled;
pcCliprdrServerCapabilities ServerCapabilities;
pcCliprdrClientCapabilities ClientCapabilities;
pcCliprdrMonitorReady MonitorReady;

View File

@ -456,6 +456,9 @@ pub type pcCliprdrServerFileContentsResponse = ::std::option::Option<
fileContentsResponse: *const CLIPRDR_FILE_CONTENTS_RESPONSE,
) -> UINT,
>;
pub type pcCheckEnabled = ::std::option::Option<
unsafe extern "C" fn(server_conn_id: UINT32, remote_conn_id: UINT32) -> BOOL,
>;
// TODO: hide more members of clipboard context
#[repr(C)]
@ -464,6 +467,7 @@ pub struct _cliprdr_client_context {
pub custom: *mut ::std::os::raw::c_void,
pub enableFiles: BOOL,
pub enableOthers: BOOL,
pub CheckEnabled: pcCheckEnabled,
pub ServerCapabilities: pcCliprdrServerCapabilities,
pub ClientCapabilities: pcCliprdrClientCapabilities,
pub MonitorReady: pcCliprdrMonitorReady,
@ -492,6 +496,11 @@ pub struct _cliprdr_client_context {
extern "C" {
pub(crate) fn init_cliprdr(context: *mut CliprdrClientContext) -> BOOL;
pub(crate) fn uninit_cliprdr(context: *mut CliprdrClientContext) -> BOOL;
pub fn empty_clipboard(
context: *mut CliprdrClientContext,
server_conn_id: u32,
remote_conn_id: u32,
) -> BOOL;
}
#[derive(Error, Debug)]
@ -508,6 +517,7 @@ impl CliprdrClientContext {
pub fn create(
enable_files: bool,
enable_others: bool,
check_enabled: pcCheckEnabled,
client_format_list: pcCliprdrClientFormatList,
client_format_list_response: pcCliprdrClientFormatListResponse,
client_format_data_request: pcCliprdrClientFormatDataRequest,
@ -519,6 +529,7 @@ impl CliprdrClientContext {
custom: 0 as *mut _,
enableFiles: if enable_files { TRUE } else { FALSE },
enableOthers: if enable_others { TRUE } else { FALSE },
CheckEnabled: check_enabled,
ServerCapabilities: None,
ClientCapabilities: None,
MonitorReady: None,

View File

@ -10,7 +10,9 @@ use hbb_common::{
use serde_derive::{Deserialize, Serialize};
use std::{
boxed::Box,
collections::HashMap,
ffi::{CStr, CString},
sync::Mutex,
};
pub mod cliprdr;
@ -66,11 +68,19 @@ pub enum ClipbaordFile {
},
}
#[derive(Default)]
struct ConnEnabled {
server_conn_enabled: HashMap<i32, bool>,
remote_conn_enabled: HashMap<i32, bool>,
}
lazy_static::lazy_static! {
static ref MSG_CHANNEL_CLIENT: (UnboundedSender<(ConnID, ClipbaordFile)>, TokioMutex<UnboundedReceiver<(ConnID, ClipbaordFile)>>) = {
let (tx, rx) = unbounded_channel();
(tx, TokioMutex::new(rx))
};
static ref CLIP_CONN_ENABLED: Mutex<ConnEnabled> = Mutex::new(ConnEnabled::default());
}
#[inline(always)]
@ -78,6 +88,16 @@ pub fn get_rx_clip_client<'a>() -> &'a TokioMutex<UnboundedReceiver<(ConnID, Cli
&MSG_CHANNEL_CLIENT.1
}
pub fn set_conn_enabled(server_conn_id: i32, remote_conn_id: i32, enabled: bool) {
let mut lock = CLIP_CONN_ENABLED.lock().unwrap();
if server_conn_id != 0 {
let _ = lock.server_conn_enabled.insert(server_conn_id, enabled);
}
if remote_conn_id != 0 {
let _ = lock.remote_conn_enabled.insert(remote_conn_id, enabled);
}
}
pub fn server_clip_file(
context: &mut Box<CliprdrClientContext>,
conn_id: ConnID,
@ -409,6 +429,7 @@ pub fn create_cliprdr_context(
Ok(CliprdrClientContext::create(
enable_files,
enable_others,
Some(check_enabled),
Some(client_format_list),
Some(client_format_list_response),
Some(client_format_data_request),
@ -418,6 +439,37 @@ pub fn create_cliprdr_context(
)?)
}
extern "C" fn check_enabled(server_conn_id: UINT32, remote_conn_id: UINT32) -> BOOL {
let lock = CLIP_CONN_ENABLED.lock().unwrap();
if server_conn_id == 0 && remote_conn_id == 0 {
return FALSE;
}
let mut server_conn_enabled = false;
if server_conn_id != 0 {
if let Some(true) = lock.server_conn_enabled.get(&(server_conn_id as i32)) {
server_conn_enabled = true;
}
} else {
server_conn_enabled = true;
}
let mut remote_conn_enabled = false;
if remote_conn_id != 0 {
if let Some(true) = lock.remote_conn_enabled.get(&(remote_conn_id as i32)) {
remote_conn_enabled = true;
}
} else {
remote_conn_enabled = true;
}
if server_conn_enabled && remote_conn_enabled {
return TRUE;
} else {
return FALSE;
}
}
extern "C" fn client_format_list(
_context: *mut CliprdrClientContext,
clip_format_list: *const CLIPRDR_FORMAT_LIST,

View File

@ -228,6 +228,8 @@ struct wf_clipboard
HANDLE response_data_event;
LPDATAOBJECT data_obj;
HANDLE data_obj_mutex;
ULONG req_fsize;
char *req_fdata;
HANDLE req_fevent;
@ -682,6 +684,10 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
return E_INVALIDARG;
clipboard = (wfClipboard *)instance->m_pData;
if (!clipboard->context->CheckEnabled(instance->m_serverConnID, instance->m_remoteConnID))
{
return E_INVALIDARG;
}
if (!clipboard)
return E_INVALIDARG;
@ -1450,12 +1456,15 @@ static UINT cliprdr_send_data_request(UINT32 serverConnID, UINT32 remoteConnID,
clipboard->requestedFormatId = formatId;
rc = clipboard->context->ClientFormatDataRequest(clipboard->context, &formatDataRequest);
if (WaitForSingleObject(clipboard->response_data_event, INFINITE) != WAIT_OBJECT_0)
rc = ERROR_INTERNAL_ERROR;
else if (!ResetEvent(clipboard->response_data_event))
rc = ERROR_INTERNAL_ERROR;
return rc;
while (clipboard->context->CheckEnabled(serverConnID, remoteConnID))
{
if (WaitForSingleObject(clipboard->response_data_event, 50) != WAIT_OBJECT_0)
rc = ERROR_INTERNAL_ERROR;
else if (!ResetEvent(clipboard->response_data_event))
rc = ERROR_INTERNAL_ERROR;
return rc;
}
return ERROR_INTERNAL_ERROR;
}
UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 serverConnID, UINT32 remoteConnID, const void *streamid, ULONG index,
@ -1480,12 +1489,15 @@ UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 serverConn
fileContentsRequest.msgFlags = 0;
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
if (WaitForSingleObject(clipboard->req_fevent, INFINITE) != WAIT_OBJECT_0)
rc = ERROR_INTERNAL_ERROR;
else if (!ResetEvent(clipboard->req_fevent))
rc = ERROR_INTERNAL_ERROR;
return rc;
while (clipboard->context->CheckEnabled(serverConnID, remoteConnID))
{
if (WaitForSingleObject(clipboard->req_fevent, INFINITE) != WAIT_OBJECT_0)
rc = ERROR_INTERNAL_ERROR;
else if (!ResetEvent(clipboard->req_fevent))
rc = ERROR_INTERNAL_ERROR;
return rc;
}
return ERROR_INTERNAL_ERROR;
}
static UINT cliprdr_send_response_filecontents(wfClipboard *clipboard, UINT32 serverConnID, UINT32 remoteConnID, UINT32 streamId, UINT32 size,
@ -1540,7 +1552,6 @@ static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM
case WM_CLIPBOARDUPDATE:
DEBUG_CLIPRDR("info: WM_CLIPBOARDUPDATE");
// if (clipboard->sync)
{
if ((GetClipboardOwner() != clipboard->hwnd) &&
@ -1632,6 +1643,11 @@ static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM
case OLE_SETCLIPBOARD:
DEBUG_CLIPRDR("info: OLE_SETCLIPBOARD");
if (WaitForSingleObject(clipboard->data_obj_mutex, INFINITE) != WAIT_OBJECT_0)
{
break;
}
if (clipboard->data_obj != NULL)
{
wf_destroy_file_obj(clipboard->data_obj);
@ -1648,6 +1664,11 @@ static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM
}
free((void *)lParam);
if (!ReleaseMutex(clipboard->data_obj_mutex))
{
// critical error!!!
}
break;
case DELAYED_RENDERING:
@ -2738,6 +2759,9 @@ BOOL wf_cliprdr_init(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
if (!(clipboard->response_data_event = CreateEvent(NULL, TRUE, FALSE, NULL)))
goto error;
if (!(clipboard->data_obj_mutex = CreateMutex(NULL, FALSE, "data_obj_mutex")))
goto error;
if (!(clipboard->req_fevent = CreateEvent(NULL, TRUE, FALSE, NULL)))
goto error;
@ -2806,3 +2830,69 @@ BOOL uninit_cliprdr(CliprdrClientContext *context)
{
return wf_cliprdr_uninit(&clipboard, context);
}
BOOL empty_cliprdr(CliprdrClientContext *context, UINT32 server_conn_id, UINT32 remote_conn_id)
{
wfClipboard *clipboard = NULL;
BOOL rc = FALSE;
if (!context)
{
return FALSE;
}
if (server_conn_id == 0 && remote_conn_id == 0)
{
return TRUE;
}
clipboard = (wfClipboard *)context->custom;
if (WaitForSingleObject(clipboard->data_obj_mutex, INFINITE) != WAIT_OBJECT_0)
{
return FALSE;
}
while (0)
{
if (clipboard->data_obj != NULL)
{
CliprdrDataObject *instance = clipboard->data_obj;
if (server_conn_id != 0 && instance->m_serverConnID != server_conn_id)
{
rc = TRUE;
break;
}
if (remote_conn_id != 0 && instance->m_remoteConnID != remote_conn_id)
{
rc = TRUE;
break;
}
wf_destroy_file_obj(clipboard->data_obj);
clipboard->data_obj = NULL;
}
/* discard all contexts in clipboard */
if (!try_open_clipboard(clipboard->hwnd))
{
DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError());
rc = FALSE;
break;
}
if (!EmptyClipboard())
{
rc = FALSE;
}
if (!CloseClipboard())
{
// critical error!!!
}
rc = TRUE;
}
if (!ReleaseMutex(clipboard->data_obj_mutex))
{
// critical error!!!
}
return rc;
}

View File

@ -74,6 +74,7 @@ pub enum Data {
clipboard: bool,
audio: bool,
file: bool,
file_transfer_enabled: bool,
},
ChatMessage {
text: String,
@ -105,6 +106,7 @@ pub enum Data {
},
SyncConfigToUserResp(bool),
ClipbaordFile(ClipbaordFile),
ClipboardFileEnabled(bool),
}
#[tokio::main(flavor = "current_thread")]

View File

@ -246,6 +246,7 @@ impl Connection {
} else if &name == "file" {
conn.file = enabled;
conn.send_permission(Permission::File, enabled).await;
conn.send_to_cm(ipc::Data::ClipboardFileEnabled(conn.file_transfer_enabled()));
}
}
ipc::Data::RawMessage(bytes) => {
@ -654,6 +655,7 @@ impl Connection {
clipboard: self.clipboard,
audio: self.audio,
file: self.file,
file_transfer_enabled: self.file_transfer_enabled(),
});
}
@ -1020,6 +1022,7 @@ impl Connection {
if let Ok(q) = o.enable_file_transfer.enum_value() {
if q != BoolOption::NotSet {
self.enable_file_transfer = q == BoolOption::Yes;
self.send_to_cm(ipc::Data::ClipboardFileEnabled(self.file_transfer_enabled()));
}
}
if let Ok(q) = o.disable_clipboard.enum_value() {

View File

@ -1,6 +1,8 @@
use crate::ipc::{self, new_listener, Connection, Data};
#[cfg(windows)]
use clipboard::{create_cliprdr_context, get_rx_clip_client, server_clip_file, ConnID};
use clipboard::{
create_cliprdr_context, get_rx_clip_client, server_clip_file, set_conn_enabled, ConnID,
};
use hbb_common::{
allow_err,
config::{Config, ICON},
@ -193,6 +195,9 @@ impl ConnectionManager {
#[cfg(windows)]
allow_err!(_tx_clip_file.send((id, _clip)));
}
Data::ClipboardFileEnabled(enabled) => {
set_conn_enabled(id, 0, enabled);
}
_ => {}
}
}
@ -361,8 +366,9 @@ async fn start_ipc(cm: ConnectionManager) {
}
Ok(Some(data)) => {
match data {
Data::Login{id, is_file_transfer, port_forward, peer_id, name, authorized, keyboard, clipboard, audio, file} => {
Data::Login{id, is_file_transfer, port_forward, peer_id, name, authorized, keyboard, clipboard, audio, file, file_transfer_enabled} => {
conn_id = id;
set_conn_enabled(id, 0, file_transfer_enabled);
cm.add_connection(id, is_file_transfer, port_forward, peer_id, name, authorized, keyboard, clipboard, audio, file, tx.clone());
}
Data::Close => {
@ -532,7 +538,7 @@ async fn start_clipboard_file(
}
#[cfg(windows)]
fn cmd_inner_send<'a>(cm: &'a ConnectionManager, id: i32, data: Data) {
fn cmd_inner_send(cm: &ConnectionManager, id: i32, data: Data) {
let lock = cm.read().unwrap();
if id != 0 {
if let Some(s) = lock.senders.get(&id) {