diff --git a/Cargo.lock b/Cargo.lock index 4b1f7f1..9cfd4b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,9 +274,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.0", diff --git a/src/cdp.rs b/src/cdp.rs index a71f386..a0925dd 100644 --- a/src/cdp.rs +++ b/src/cdp.rs @@ -1422,7 +1422,7 @@ impl Executor for CdpExecutor { } } -fn fetch_json_targets(config: &CdpConfig) -> Result { +fn discover_websocket_url(config: &CdpConfig) -> Result { let mut stream = TcpStream::connect_timeout(&config.endpoint(), MAX_IO_TIMEOUT) .map_err(|_| CdpError::Protocol)?; stream @@ -1486,11 +1486,7 @@ fn fetch_json_targets(config: &CdpConfig) -> Result { if body.len() != content_length { return Err(CdpError::Protocol); } - serde_json::from_slice(&body).map_err(|_| CdpError::Protocol) -} - -fn discover_websocket_url(config: &CdpConfig) -> Result { - let targets = fetch_json_targets(config)?; + let targets: Value = serde_json::from_slice(&body).map_err(|_| CdpError::Protocol)?; let mut matches = targets .as_array() .ok_or(CdpError::Protocol)? @@ -1745,7 +1741,7 @@ fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result= descriptors.len() || written % 8 != 0 { return Err(CdpError::StaleTarget); } - for descriptor in descriptors[..written].as_chunks::<8>().0 { + for descriptor in descriptors[..written].chunks(8) { let file_descriptor = i32::from_ne_bytes(descriptor[..4].try_into().map_err(|_| CdpError::Protocol)?); let descriptor_type = u32::from_ne_bytes( @@ -1784,12 +1780,14 @@ fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result Result, CdpError> { +fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result, CdpError> { const AF_INET: u32 = 2; const ERROR_INSUFFICIENT_BUFFER: u32 = 122; const MAX_TABLE_BYTES: usize = 16 * 1024 * 1024; const NO_ERROR: u32 = 0; + const TCP_LISTEN: u32 = 2; const TCP_TABLE_OWNER_PID_LISTENER: i32 = 3; + const TCP_ROW_BYTES: usize = 24; #[link(name = "iphlpapi")] unsafe extern "system" { @@ -1840,16 +1838,6 @@ fn get_extended_tcp_table() -> Result, CdpError> { if written > table.len() || written < 4 { return Err(CdpError::Protocol); } - table.truncate(written); - Ok(table) -} - -#[cfg(windows)] -fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result, CdpError> { - const TCP_LISTEN: u32 = 2; - const TCP_ROW_BYTES: usize = 24; - - let table = get_extended_tcp_table()?; let row_count = u32::from_ne_bytes(table[..4].try_into().map_err(|_| CdpError::Protocol)?) as usize; if 4usize @@ -1858,17 +1846,12 @@ fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result table.len()) + .is_none_or(|required| required > written) { return Err(CdpError::Protocol); } let mut owners = BTreeSet::new(); - for row in table[4..] - .as_chunks::() - .0 - .iter() - .take(row_count) - { + for row in table[4..].chunks(TCP_ROW_BYTES).take(row_count) { if u32::from_ne_bytes(row[..4].try_into().map_err(|_| CdpError::Protocol)?) == TCP_LISTEN && row[4..8] == Ipv4Addr::LOCALHOST.octets() && u16::from_be_bytes(row[8..10].try_into().map_err(|_| CdpError::Protocol)?) == port @@ -2762,44 +2745,6 @@ mod tests { } } - fn interactive_request( - operation_id: &str, - action: Action, - target: TargetRef, - verification: VerificationPolicy, - ) -> ActionRequest { - ActionRequest { - protocol_version: PROTOCOL_VERSION, - action_version: PROTOCOL_VERSION, - target_version: PROTOCOL_VERSION, - verification_version: PROTOCOL_VERSION, - operation_id: operation_id.to_string(), - subject: "subject".to_string(), - session_id: "session".to_string(), - authority: SignedAuthority { - grant: AuthorityGrant { - protocol_version: PROTOCOL_VERSION, - issuer: "host".to_string(), - key_id: "key".to_string(), - operation_id: operation_id.to_string(), - subject: "subject".to_string(), - session_id: "session".to_string(), - risk: SafetyClass::Reversible, - expires_at_ms: i64::MAX, - policy_generation: "generation".to_string(), - action_hash: "0".repeat(64), - }, - signature: "0".repeat(128), - }, - action, - target, - interaction_mode: crate::InteractionMode::Interactive, - deadline_at_ms: i64::MAX, - verification, - safety: SafetyClass::Reversible, - } - } - #[test] fn only_exact_local_channel_is_accepted() { let process_id = std::process::id(); @@ -3837,14 +3782,38 @@ mod tests { )), ]); drop(channel); - let request = interactive_request( - "cdp-set-value", - Action::SetValue { + let request = ActionRequest { + protocol_version: PROTOCOL_VERSION, + action_version: PROTOCOL_VERSION, + target_version: PROTOCOL_VERSION, + verification_version: PROTOCOL_VERSION, + operation_id: "cdp-set-value".to_string(), + subject: "subject".to_string(), + session_id: "session".to_string(), + authority: SignedAuthority { + grant: AuthorityGrant { + protocol_version: PROTOCOL_VERSION, + issuer: "host".to_string(), + key_id: "key".to_string(), + operation_id: "cdp-set-value".to_string(), + subject: "subject".to_string(), + session_id: "session".to_string(), + risk: SafetyClass::Reversible, + expires_at_ms: i64::MAX, + policy_generation: "generation".to_string(), + action_hash: "0".repeat(64), + }, + signature: "0".repeat(128), + }, + action: Action::SetValue { value: value.to_string(), }, - TargetRef::Element { target }, - VerificationPolicy::TargetValueHash { sha256: value_hash }, - ); + target: TargetRef::Element { target }, + interaction_mode: crate::InteractionMode::Interactive, + deadline_at_ms: i64::MAX, + verification: VerificationPolicy::TargetValueHash { sha256: value_hash }, + safety: SafetyClass::Reversible, + }; let directory = tempfile::tempdir().expect("temporary directory"); crate::restrict_directory(directory.path()).expect("restrict temporary directory"); let report = Engine::new( diff --git a/src/lib.rs b/src/lib.rs index ee9a91b..0dd0ce3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,3 @@ -#![allow(unknown_lints)] -#![allow(clippy::chunks_exact_to_as_chunks)] #![allow(clippy::collapsible_if, clippy::needless_return)] use std::collections::BTreeMap; use std::fs::{File, OpenOptions}; @@ -130,17 +128,6 @@ pub enum DeliveryRoute { Unknown, } -impl DeliveryRoute { - pub fn as_str(&self) -> &'static str { - match self { - DeliveryRoute::TargetAddressed => "targetAddressed", - DeliveryRoute::Pointer => "pointer", - DeliveryRoute::PerProcessEvent => "perProcessEvent", - DeliveryRoute::Unknown => "unknown", - } - } -} - #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum BackgroundSupport { @@ -1267,11 +1254,69 @@ impl NativeRuntime { } #[cfg(windows)] { - return windows_native_press(_key, _count, _delay_ms); + use windows::Win32::UI::Input::KeyboardAndMouse::*; + + let vk = win_key_code(_key).ok_or(NativeError)?; + + for i in 0.._count { + if i > 0 { + if let Some(delay) = _delay_ms { + std::thread::sleep(std::time::Duration::from_millis(delay)); + } + } + let down = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: vk, + wScan: 0, + dwFlags: KEYBD_EVENT_FLAGS::default(), + time: 0, + dwExtraInfo: 0, + }, + }, + }; + let up = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: vk, + wScan: 0, + dwFlags: KEYEVENTF_KEYUP, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + let _ = unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) }; + } + return Ok(()); } #[cfg(target_os = "macos")] { - return macos_native_press(_key, _count, _delay_ms); + if !native_permissions() + .get("accessibility") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + { + return Err(NativeError); + } + let code = mac_key_name_code(_key) + .or_else(|| { + _key.chars() + .next() + .and_then(|ch| mac_key_code(ch.to_ascii_lowercase())) + }) + .ok_or(NativeError)?; + for i in 0.._count { + if i > 0 + && let Some(delay) = _delay_ms + { + std::thread::sleep(std::time::Duration::from_millis(delay)); + } + let _ = mac_post_key(code, 0); + } + Ok(()) } #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] Err(NativeError) @@ -1918,95 +1963,105 @@ fn native_drag( } } +#[cfg(windows)] +fn native_click_windows(point: &NativePoint, button: &str) -> Result<(), NativeError> { + use windows::Win32::UI::Input::KeyboardAndMouse::*; + use windows::Win32::UI::WindowsAndMessaging::SetCursorPos; + + if unsafe { SetCursorPos(point.x as i32, point.y as i32) }.is_err() { + return Err(NativeError); + } + let (down_flags, up_flags) = match button { + "left" => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP), + "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP), + "middle" => (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP), + _ => return Err(NativeError), + }; + let down = INPUT { + r#type: INPUT_MOUSE, + Anonymous: INPUT_0 { + mi: MOUSEINPUT { + dx: 0, + dy: 0, + mouseData: 0, + dwFlags: down_flags, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + let up = INPUT { + r#type: INPUT_MOUSE, + Anonymous: INPUT_0 { + mi: MOUSEINPUT { + dx: 0, + dy: 0, + mouseData: 0, + dwFlags: up_flags, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + if unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) } != 2 { + return Err(NativeError); + } + return Ok(()); +} + +#[cfg(target_os = "macos")] +fn native_click_macos(point: &NativePoint, button: &str) -> Result<(), NativeError> { + use core_graphics::event::{CGEvent, CGEventType, CGMouseButton}; + use core_graphics::event_source::{CGEventSource, CGEventSourceStateID}; + use core_graphics::geometry::CGPoint; + + if !native_permissions() + .get("accessibility") + .and_then(Value::as_bool) + .unwrap_or(false) + { + return Err(NativeError); + } + let (down, up, mouse_button) = match button { + "left" => ( + CGEventType::LeftMouseDown, + CGEventType::LeftMouseUp, + CGMouseButton::Left, + ), + "right" => ( + CGEventType::RightMouseDown, + CGEventType::RightMouseUp, + CGMouseButton::Right, + ), + "middle" => ( + CGEventType::OtherMouseDown, + CGEventType::OtherMouseUp, + CGMouseButton::Center, + ), + _ => return Err(NativeError), + }; + let position = CGPoint::new(point.x as f64, point.y as f64); + let down_source = + CGEventSource::new(CGEventSourceStateID::CombinedSessionState).map_err(|_| NativeError)?; + let down_event = CGEvent::new_mouse_event(down_source, down, position, mouse_button) + .map_err(|_| NativeError)?; + let up_source = + CGEventSource::new(CGEventSourceStateID::CombinedSessionState).map_err(|_| NativeError)?; + let up_event = + CGEvent::new_mouse_event(up_source, up, position, mouse_button).map_err(|_| NativeError)?; + mac_post_event(&down_event)?; + mac_post_event(&up_event)?; + Ok(()) +} + fn native_click(point: &NativePoint, button: &str) -> Result<(), NativeError> { #[cfg(target_os = "macos")] { - use core_graphics::event::{CGEvent, CGEventType, CGMouseButton}; - use core_graphics::event_source::{CGEventSource, CGEventSourceStateID}; - use core_graphics::geometry::CGPoint; - - if !native_permissions() - .get("accessibility") - .and_then(Value::as_bool) - .unwrap_or(false) - { - return Err(NativeError); - } - let (down, up, mouse_button) = match button { - "left" => ( - CGEventType::LeftMouseDown, - CGEventType::LeftMouseUp, - CGMouseButton::Left, - ), - "right" => ( - CGEventType::RightMouseDown, - CGEventType::RightMouseUp, - CGMouseButton::Right, - ), - "middle" => ( - CGEventType::OtherMouseDown, - CGEventType::OtherMouseUp, - CGMouseButton::Center, - ), - _ => return Err(NativeError), - }; - let position = CGPoint::new(point.x as f64, point.y as f64); - let down_source = CGEventSource::new(CGEventSourceStateID::CombinedSessionState) - .map_err(|_| NativeError)?; - let down_event = CGEvent::new_mouse_event(down_source, down, position, mouse_button) - .map_err(|_| NativeError)?; - let up_source = CGEventSource::new(CGEventSourceStateID::CombinedSessionState) - .map_err(|_| NativeError)?; - let up_event = CGEvent::new_mouse_event(up_source, up, position, mouse_button) - .map_err(|_| NativeError)?; - mac_post_event(&down_event)?; - mac_post_event(&up_event)?; - Ok(()) + return native_click_macos(point, button); } #[cfg(windows)] { - use windows::Win32::UI::Input::KeyboardAndMouse::*; - use windows::Win32::UI::WindowsAndMessaging::SetCursorPos; - - if unsafe { SetCursorPos(point.x as i32, point.y as i32) }.is_err() { - return Err(NativeError); - } - let (down_flags, up_flags) = match button { - "left" => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP), - "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP), - "middle" => (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP), - _ => return Err(NativeError), - }; - let down = INPUT { - r#type: INPUT_MOUSE, - Anonymous: INPUT_0 { - mi: MOUSEINPUT { - dx: 0, - dy: 0, - mouseData: 0, - dwFlags: down_flags, - time: 0, - dwExtraInfo: 0, - }, - }, - }; - let up = INPUT { - r#type: INPUT_MOUSE, - Anonymous: INPUT_0 { - mi: MOUSEINPUT { - dx: 0, - dy: 0, - mouseData: 0, - dwFlags: up_flags, - time: 0, - dwExtraInfo: 0, - }, - }, - }; - if unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) } != 2 { - return Err(NativeError); - } - return Ok(()); + return native_click_windows(point, button); } #[cfg(target_os = "linux")] { @@ -6759,7 +6814,7 @@ impl Drop for LedgerLock { } } -fn validate_request_versions(request: &ActionRequest) -> Result<(), ProtocolError> { +fn validate_request(request: &ActionRequest) -> Result<(), ProtocolError> { if request.protocol_version != PROTOCOL_VERSION || request.action_version != PROTOCOL_VERSION || request.target_version != PROTOCOL_VERSION @@ -6770,10 +6825,6 @@ fn validate_request_versions(request: &ActionRequest) -> Result<(), ProtocolErro "unsupported protocol version".to_string(), )); } - Ok(()) -} - -fn validate_request_identifiers(request: &ActionRequest) -> Result<(), ProtocolError> { for (name, value) in [ ("operation_id", request.operation_id.as_str()), ("subject", request.subject.as_str()), @@ -6788,10 +6839,6 @@ fn validate_request_identifiers(request: &ActionRequest) -> Result<(), ProtocolE return Err(ProtocolError::InvalidRequest(format!("invalid {name}"))); } } - Ok(()) -} - -fn validate_request_action_and_target(request: &ActionRequest) -> Result<(), ProtocolError> { let auxiliary = matches!( request.action, Action::Screenshot { .. } @@ -6840,10 +6887,6 @@ fn validate_request_action_and_target(request: &ActionRequest) -> Result<(), Pro "action requires a fenced semantic element target".to_string(), )); } - Ok(()) -} - -fn validate_request_verification(request: &ActionRequest) -> Result<(), ProtocolError> { validate_verification(&request.verification)?; match (&request.action, &request.verification) { (Action::SetValue { value }, VerificationPolicy::TargetValueHash { sha256 }) @@ -6903,14 +6946,6 @@ fn validate_request_verification(request: &ActionRequest) -> Result<(), Protocol Ok(()) } -fn validate_request(request: &ActionRequest) -> Result<(), ProtocolError> { - validate_request_versions(request)?; - validate_request_identifiers(request)?; - validate_request_action_and_target(request)?; - validate_request_verification(request)?; - Ok(()) -} - fn target_provenance_is_valid(target: &TargetRef) -> bool { match target { TargetRef::Coordinates { @@ -7874,78 +7909,6 @@ fn default_ledger_path_with_env(get_env: impl Fn(&str) -> Option, -) -> Result<(), NativeError> { - use windows::Win32::UI::Input::KeyboardAndMouse::*; - - let vk = win_key_code(_key).ok_or(NativeError)?; - - for i in 0.._count { - if i > 0 { - if let Some(delay) = _delay_ms { - std::thread::sleep(std::time::Duration::from_millis(delay)); - } - } - let down = INPUT { - r#type: INPUT_KEYBOARD, - Anonymous: INPUT_0 { - ki: KEYBDINPUT { - wVk: vk, - wScan: 0, - dwFlags: KEYBD_EVENT_FLAGS::default(), - time: 0, - dwExtraInfo: 0, - }, - }, - }; - let up = INPUT { - r#type: INPUT_KEYBOARD, - Anonymous: INPUT_0 { - ki: KEYBDINPUT { - wVk: vk, - wScan: 0, - dwFlags: KEYEVENTF_KEYUP, - time: 0, - dwExtraInfo: 0, - }, - }, - }; - let _ = unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) }; - } - Ok(()) -} - -#[cfg(target_os = "macos")] -fn macos_native_press(_key: &str, _count: u32, _delay_ms: Option) -> Result<(), NativeError> { - if !native_permissions() - .get("accessibility") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { - return Err(NativeError); - } - let code = mac_key_name_code(_key) - .or_else(|| { - _key.chars() - .next() - .and_then(|ch| mac_key_code(ch.to_ascii_lowercase())) - }) - .ok_or(NativeError)?; - for i in 0.._count { - if i > 0 - && let Some(delay) = _delay_ms - { - std::thread::sleep(std::time::Duration::from_millis(delay)); - } - let _ = mac_post_key(code, 0); - } - Ok(()) -} - #[cfg(test)] mod tests { use super::{ @@ -8109,15 +8072,6 @@ mod tests { ); } - #[test] - fn test_delivery_route_as_str() { - use super::DeliveryRoute; - assert_eq!(DeliveryRoute::TargetAddressed.as_str(), "targetAddressed"); - assert_eq!(DeliveryRoute::Pointer.as_str(), "pointer"); - assert_eq!(DeliveryRoute::PerProcessEvent.as_str(), "perProcessEvent"); - assert_eq!(DeliveryRoute::Unknown.as_str(), "unknown"); - } - #[cfg(target_os = "macos")] #[test] fn macos_semantic_scroll_names_one_page_action_per_direction() { diff --git a/src/main.rs b/src/main.rs index 133a787..2280417 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,3 @@ -#![allow(unknown_lints)] -#![allow(clippy::chunks_exact_to_as_chunks)] use std::io; use std::path::PathBuf; use std::process::ExitCode;