improve (tighten) scoping of unsafe blocks

This commit is contained in:
2025-09-13 16:50:44 +01:00
parent 445b63fa4c
commit 5c73ee7bd5
5 changed files with 53 additions and 65 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ impl AntiAfk {
fn send(vk_codes: &[VIRTUAL_KEY]) { fn send(vk_codes: &[VIRTUAL_KEY]) {
let mut inputs = Vec::new(); let mut inputs = Vec::new();
for &vk_code in vk_codes { for &vk_code in vk_codes {
let scan_code = unsafe { MapVirtualKeyW(u32::from(vk_code.0), MAPVK_VK_TO_VSC) as u16 }; let scan_code = unsafe { MapVirtualKeyW(u32::from(vk_code.0), MAPVK_VK_TO_VSC) } as u16;
for event in [KEYBD_EVENT_FLAGS(0), KEYEVENTF_KEYUP] { for event in [KEYBD_EVENT_FLAGS(0), KEYEVENTF_KEYUP] {
let mut input = INPUT { let mut input = INPUT {
r#type: INPUT_KEYBOARD, r#type: INPUT_KEYBOARD,
+10 -14
View File
@@ -62,25 +62,21 @@ pub fn activate(game_handle: &mut HANDLE, system_info: &mut SystemInfo) -> Resul
let Some(pid) = get_gta_pid(system_info) else { let Some(pid) = get_gta_pid(system_info) else {
return Err(()); return Err(());
}; };
unsafe { match unsafe { OpenProcess(PROCESS_SUSPEND_RESUME, false, pid) } {
match OpenProcess(PROCESS_SUSPEND_RESUME, false, pid) { Ok(handle) => *game_handle = handle,
Ok(handle) => *game_handle = handle, Err(why) => {
Err(why) => { let message = format!("failed to suspend game for empty session:\n{why}");
let message = format!("failed to suspend game for empty session:\n{why}"); log::log(log::LogLevel::Error, &message);
log::log(log::LogLevel::Error, &message); return Err(());
return Err(());
}
} }
let _ = NtSuspendProcess(*game_handle);
} }
let _ = unsafe { NtSuspendProcess(*game_handle) };
Ok(()) Ok(())
} }
pub fn deactivate(game_handle: &mut HANDLE) { pub fn deactivate(game_handle: &mut HANDLE) {
unsafe { if !game_handle.is_invalid() {
if !game_handle.is_invalid() { let _ = unsafe { NtResumeProcess(*game_handle) };
let _ = NtResumeProcess(*game_handle); let _ = unsafe { CloseHandle(*game_handle) };
let _ = CloseHandle(*game_handle);
}
} }
} }
+21 -25
View File
@@ -64,10 +64,8 @@ impl Default for GameNetworking {
impl Drop for GameNetworking { impl Drop for GameNetworking {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { if self.com_initialized {
if self.com_initialized { unsafe { CoUninitialize() };
CoUninitialize();
}
} }
} }
} }
@@ -79,44 +77,42 @@ impl GameNetworking {
return; return;
}; };
let policy: INetFwPolicy2 = let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() }; unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER) }.unwrap();
let rules = unsafe { policy.Rules().unwrap() }; let rules = unsafe { policy.Rules() }.unwrap();
let exe_path = BSTR::from(exe_path.to_string_lossy().to_string()); let exe_path = BSTR::from(exe_path.to_string_lossy().to_string());
for filter in [ for filter in [
(FILTER_NAME_IN, NET_FW_RULE_DIR_IN), (FILTER_NAME_IN, NET_FW_RULE_DIR_IN),
(FILTER_NAME_OUT, NET_FW_RULE_DIR_OUT), (FILTER_NAME_OUT, NET_FW_RULE_DIR_OUT),
] { ] {
let _ = unsafe { rules.Remove(&BSTR::from(filter.0)) }; let _ = unsafe { rules.Remove(&BSTR::from(filter.0)) };
unsafe { let rule: INetFwRule =
let rule: INetFwRule = unsafe { CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER) }.unwrap();
CoCreateInstance(&NetFwRule, None, CLSCTX_INPROC_SERVER).unwrap(); unsafe { rule.SetName(&BSTR::from(filter.0)) }.unwrap();
rule.SetName(&BSTR::from(filter.0)).unwrap(); unsafe { rule.SetApplicationName(&exe_path) }.unwrap();
rule.SetApplicationName(&exe_path).unwrap(); unsafe { rule.SetDirection(filter.1) }.unwrap();
rule.SetDirection(filter.1).unwrap(); unsafe { rule.SetEnabled(true.into()) }.unwrap();
rule.SetEnabled(true.into()).unwrap(); unsafe { rule.SetAction(NET_FW_ACTION_BLOCK) }.unwrap();
rule.SetAction(NET_FW_ACTION_BLOCK).unwrap(); unsafe { rule.SetProtocol(NET_FW_IP_PROTOCOL_ANY.0) }.unwrap();
rule.SetProtocol(NET_FW_IP_PROTOCOL_ANY.0).unwrap(); unsafe { rules.Add(&rule) }.unwrap();
rules.Add(&rule).unwrap();
}
} }
self.blocked_status = Self::is_blocked().into(); self.blocked_status = Self::is_blocked().into();
} }
pub fn unblock_all(&mut self) { pub fn unblock_all(&mut self) {
let policy: INetFwPolicy2 = let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() }; unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER) }.unwrap();
let rules = unsafe { policy.Rules().unwrap() }; let rules = unsafe { policy.Rules() }.unwrap();
unsafe { rules.Remove(&BSTR::from(FILTER_NAME_IN)).unwrap() }; unsafe { rules.Remove(&BSTR::from(FILTER_NAME_IN)) }.unwrap();
unsafe { rules.Remove(&BSTR::from(FILTER_NAME_OUT)).unwrap() }; unsafe { rules.Remove(&BSTR::from(FILTER_NAME_OUT)) }.unwrap();
self.blocked_status = Self::is_blocked().into(); self.blocked_status = Self::is_blocked().into();
} }
fn is_blocked() -> bool { fn is_blocked() -> bool {
let policy: INetFwPolicy2 = let policy: INetFwPolicy2 =
unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER).unwrap() }; unsafe { CoCreateInstance(&NetFwPolicy2, None, CLSCTX_INPROC_SERVER) }.unwrap();
let rules = unsafe { policy.Rules().unwrap() }; let rules = unsafe { policy.Rules() }.unwrap();
let in_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_IN)).is_ok() }; let in_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_IN)) }.is_ok();
let out_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_OUT)).is_ok() }; let out_rule_exists = unsafe { rules.Item(&BSTR::from(FILTER_NAME_OUT)) }.is_ok();
in_rule_exists || out_rule_exists in_rule_exists || out_rule_exists
} }
+4 -4
View File
@@ -21,10 +21,10 @@ impl App {
use windows::Win32::UI::WindowsAndMessaging::{ use windows::Win32::UI::WindowsAndMessaging::{
GetForegroundWindow, GetWindowTextW, GetForegroundWindow, GetWindowTextW,
}; };
let mut buffer = [0; 512]; let current_title = {
let current_title = unsafe { let mut buffer = [0; 512];
let hwnd = GetForegroundWindow(); let hwnd = unsafe { GetForegroundWindow() };
let length = GetWindowTextW(hwnd, &mut buffer); let length = unsafe { GetWindowTextW(hwnd, &mut buffer) };
String::from_utf16_lossy(&buffer[..length as usize]) String::from_utf16_lossy(&buffer[..length as usize])
}; };
ui.label(format!("focused: \"{current_title}\"")); ui.label(format!("focused: \"{current_title}\""));
+17 -21
View File
@@ -25,25 +25,21 @@ pub fn is_cursor_visible() -> bool {
cbSize: u32::try_from(std::mem::size_of::<CURSORINFO>()).unwrap(), cbSize: u32::try_from(std::mem::size_of::<CURSORINFO>()).unwrap(),
..Default::default() ..Default::default()
}; };
unsafe { unsafe { GetCursorInfo(&raw mut ci) }.unwrap();
GetCursorInfo(&raw mut ci).unwrap();
}
ci.flags == CURSOR_SHOWING ci.flags == CURSOR_SHOWING
} }
pub fn is_window_focused(target_title: &str) -> bool { pub fn is_window_focused(target_title: &str) -> bool {
let mut buffer = [0; 512]; let mut buffer = [0; 512];
unsafe { let hwnd = unsafe { GetForegroundWindow() };
let hwnd = GetForegroundWindow(); let length = unsafe { GetWindowTextW(hwnd, &mut buffer) };
let length = GetWindowTextW(hwnd, &mut buffer); let current_title = String::from_utf16_lossy(&buffer[..length as usize]);
let current_title = String::from_utf16_lossy(&buffer[..length as usize]); current_title == target_title
current_title == target_title
}
} }
pub fn is_any_key_pressed(keys: &[VIRTUAL_KEY]) -> bool { pub fn is_any_key_pressed(keys: &[VIRTUAL_KEY]) -> bool {
keys.iter() keys.iter()
.any(|&key| unsafe { (GetAsyncKeyState(i32::from(key.0)) & i16::MIN) != 0 }) .any(|&key| unsafe { GetAsyncKeyState(i32::from(key.0)) } & i16::MIN != 0)
} }
pub fn elevate(closing: ElevationExitMethod) { pub fn elevate(closing: ElevationExitMethod) {
@@ -66,22 +62,22 @@ pub fn elevate(closing: ElevationExitMethod) {
pub fn is_elevated() -> bool { pub fn is_elevated() -> bool {
let mut token: HANDLE = HANDLE::default(); let mut token: HANDLE = HANDLE::default();
unsafe { if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut token) }.is_err() {
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &raw mut token).is_err() { return false;
return false; }
} let mut elevation = TOKEN_ELEVATION::default();
let mut elevation = TOKEN_ELEVATION::default(); let mut size = u32::try_from(std::mem::size_of::<TOKEN_ELEVATION>()).unwrap();
let mut size = u32::try_from(std::mem::size_of::<TOKEN_ELEVATION>()).unwrap(); let result = unsafe {
let result = GetTokenInformation( GetTokenInformation(
token, token,
TokenElevation, TokenElevation,
Some((&raw mut elevation).cast()), Some((&raw mut elevation).cast()),
size, size,
&raw mut size, &raw mut size,
); )
CloseHandle(token).unwrap(); };
result.is_ok() && elevation.TokenIsElevated != 0 unsafe { CloseHandle(token) }.unwrap();
} result.is_ok() && elevation.TokenIsElevated != 0
} }
pub fn is_system_theme_dark() -> bool { pub fn is_system_theme_dark() -> bool {