Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use windows-sys instead of winapi #660

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ uzers = "0.12"
which = "6"

[target.'cfg(target_os = "windows")'.dependencies]
winapi = { version = "0.3", features = ["handleapi", "minwindef", "psapi", "securitybaseapi", "tlhelp32", "winbase", "winnt", "iphlpapi"] }
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Networking_WinSock", "Win32_NetworkManagement_IpHelper", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_ProcessStatus", "Win32_System_Threading"] }

[target.'cfg(target_os = "freebsd")'.dependencies]
bsd-kvm = "0.1.5"
Expand Down
18 changes: 7 additions & 11 deletions src/columns/tcp_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,11 @@ use std::collections::HashMap;
#[cfg(target_os = "windows")]
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
#[cfg(target_os = "windows")]
use winapi::shared::tcpmib::MIB_TCP_STATE;
use windows_sys::Win32::NetworkManagement::IpHelper::{GetTcpTable2, GetTcp6Table2, MIB_TCP_STATE, MIB_TCPTABLE2, MIB_TCP_STATE_LISTEN, MIB_TCP6TABLE2};
#[cfg(target_os = "windows")]
use winapi::shared::tcpmib::{MIB_TCPTABLE2, MIB_TCP_STATE_LISTEN};
use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, NO_ERROR};
#[cfg(target_os = "windows")]
use winapi::shared::winerror::{ERROR_INSUFFICIENT_BUFFER, NO_ERROR};
#[cfg(target_os = "windows")]
use winapi::um::{iphlpapi::GetTcpTable2, winsock2::ntohl, winsock2::ntohs};
#[cfg(target_os = "windows")]
use winapi::{shared::tcpmib::MIB_TCP6TABLE2, um::iphlpapi::GetTcp6Table2};
use windows_sys::Win32::Networking::WinSock::{ntohl, ntohs};

pub struct TcpPort {
header: String,
Expand Down Expand Up @@ -250,7 +246,7 @@ fn get_tcp_entry_list() -> Result<Vec<TcpNetEntry>, anyhow::Error> {
unsafe { ntohs(entry.dwRemotePort as u16) },
)),
pid: entry.dwOwningPid,
state: entry.dwState,
state: entry.dwState as i32,
});
}

Expand Down Expand Up @@ -284,13 +280,13 @@ fn get_tcp6_entry_list() -> Result<Vec<TcpNetEntry>, anyhow::Error> {
let entry = unsafe { *tcp_table.table.as_ptr().add(i as usize) };
entry_list.push(TcpNetEntry {
local_address: SocketAddr::V6(SocketAddrV6::new(
Ipv6Addr::from(unsafe { *entry.LocalAddr.u.Byte() }),
Ipv6Addr::from(u128::from_be_bytes(unsafe { entry.LocalAddr.u.Byte })),
unsafe { ntohs(entry.dwLocalPort as u16) },
0,
entry.dwLocalScopeId,
)),
remote_address: SocketAddr::V6(SocketAddrV6::new(
Ipv6Addr::from(unsafe { *entry.RemoteAddr.u.Byte() }),
Ipv6Addr::from(u128::from_be_bytes(unsafe { entry.RemoteAddr.u.Byte })),
unsafe { ntohs(entry.dwRemotePort as u16) },
0,
entry.dwRemoteScopeId,
Expand All @@ -308,7 +304,7 @@ fn get_tcp6_entry_list() -> Result<Vec<TcpNetEntry>, anyhow::Error> {
mod tests {
use std::net::TcpListener;

use winapi::shared::tcpmib::MIB_TCP_STATE_LISTEN;
use windows_sys::Win32::NetworkManagement::IpHelper::MIB_TCP_STATE_LISTEN;

use super::TcpPort;

Expand Down
2 changes: 1 addition & 1 deletion src/columns/usage_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::collections::HashMap;
#[cfg(target_os = "windows")]
use std::mem::{size_of, zeroed};
#[cfg(target_os = "windows")]
use winapi::um::psapi::{GetPerformanceInfo, PERFORMANCE_INFORMATION};
use windows_sys::Win32::System::ProcessStatus::{GetPerformanceInfo, PERFORMANCE_INFORMATION};

pub struct UsageMem {
header: String,
Expand Down
65 changes: 33 additions & 32 deletions src/process/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,29 @@ use chrono::offset::TimeZone;
use chrono::{Local, NaiveDate};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
use std::mem::{size_of, zeroed, MaybeUninit};
use std::ptr;
use std::thread;
use std::time::{Duration, Instant};
use winapi::ctypes::c_void;
use winapi::shared::minwindef::{DWORD, FALSE, FILETIME, MAX_PATH};
use winapi::um::handleapi::CloseHandle;
use winapi::um::processthreadsapi::{
GetCurrentProcess, GetPriorityClass, GetProcessTimes, OpenProcess, OpenProcessToken,
use windows_sys::Win32::Foundation::{
CloseHandle, FALSE, FILETIME, HANDLE, HMODULE, MAX_PATH, PSID,
};
use winapi::um::psapi::{
EnumProcessModulesEx, GetModuleBaseNameW, GetProcessMemoryInfo, K32EnumProcesses,
LIST_MODULES_ALL, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX,
use windows_sys::Win32::Security::{
AdjustTokenPrivileges, GetTokenInformation, LookupAccountSidW, LookupPrivilegeValueW,
TokenGroups, TokenUser, SE_DEBUG_NAME, SE_PRIVILEGE_ENABLED, SID, TOKEN_ADJUST_PRIVILEGES,
TOKEN_GROUPS, TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use winapi::um::securitybaseapi::{AdjustTokenPrivileges, GetTokenInformation};
use winapi::um::tlhelp32::{
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS,
};
use winapi::um::winbase::{GetProcessIoCounters, LookupAccountSidW, LookupPrivilegeValueW};
use winapi::um::winnt::{
TokenGroups, TokenUser, HANDLE, IO_COUNTERS, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ, PSID,
SE_DEBUG_NAME, SE_PRIVILEGE_ENABLED, SID, TOKEN_ADJUST_PRIVILEGES, TOKEN_GROUPS,
TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
use windows_sys::Win32::System::ProcessStatus::{
EnumProcessModulesEx, GetModuleBaseNameW, GetProcessMemoryInfo, K32EnumProcesses,
LIST_MODULES_ALL, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, GetPriorityClass, GetProcessIoCounters, GetProcessTimes, OpenProcess,
OpenProcessToken, IO_COUNTERS, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ,
};

pub struct ProcessInfo {
Expand Down Expand Up @@ -211,7 +211,9 @@ fn set_privilege() -> bool {
}

let mut tps: TOKEN_PRIVILEGES = unsafe { zeroed() };
let se_debug_name: Vec<u16> = format!("{}\0", SE_DEBUG_NAME).encode_utf16().collect();
let se_debug_name: Vec<u16> = format!("{}\0", unsafe { *SE_DEBUG_NAME })
.encode_utf16()
.collect();
tps.PrivilegeCount = 1;
let ret = unsafe {
LookupPrivilegeValueW(
Expand All @@ -229,7 +231,7 @@ fn set_privilege() -> bool {
AdjustTokenPrivileges(
token,
FALSE,
&mut tps,
&tps as *const _,
0,
ptr::null::<TOKEN_PRIVILEGES>() as *mut TOKEN_PRIVILEGES,
ptr::null::<u32>() as *mut u32,
Expand All @@ -243,22 +245,22 @@ fn set_privilege() -> bool {
}

fn get_pids() -> Vec<i32> {
let dword_size = size_of::<DWORD>();
let mut pids: Vec<DWORD> = Vec::with_capacity(10192);
let dword_size = size_of::<u32>();
let mut pids = Vec::with_capacity(10192);
let mut cb_needed = 0;

unsafe { pids.set_len(10192) };
let result = unsafe {
K32EnumProcesses(
pids.as_mut_ptr(),
(dword_size * pids.len()) as DWORD,
(dword_size * pids.len()) as u32,
&mut cb_needed,
)
};
if result == 0 {
return Vec::new();
}
let pids_len = cb_needed / dword_size as DWORD;
let pids_len = cb_needed / dword_size as u32;
unsafe { pids.set_len(pids_len as usize) };

pids.iter().map(|x| *x as i32).collect()
Expand Down Expand Up @@ -293,11 +295,11 @@ fn get_handle(pid: i32) -> Option<HANDLE> {
OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
pid as DWORD,
pid as u32,
)
};

if handle.is_null() {
if handle == 0 {
None
} else {
Some(handle)
Expand Down Expand Up @@ -339,7 +341,7 @@ fn get_memory_info(handle: HANDLE) -> Option<MemoryInfo> {
handle,
&mut pmc as *mut PROCESS_MEMORY_COUNTERS_EX as *mut c_void
as *mut PROCESS_MEMORY_COUNTERS,
size_of::<PROCESS_MEMORY_COUNTERS_EX>() as DWORD,
size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,
)
};

Expand All @@ -363,15 +365,15 @@ fn get_memory_info(handle: HANDLE) -> Option<MemoryInfo> {
}

fn get_command(handle: HANDLE) -> Option<String> {
let mut exe_buf = [0u16; MAX_PATH + 1];
let mut h_mod = std::ptr::null_mut();
let mut exe_buf = [0u16; MAX_PATH as usize + 1];
let h_mod: HMODULE = 0;
let mut cb_needed = 0;

let ret = unsafe {
EnumProcessModulesEx(
handle,
&mut h_mod,
size_of::<DWORD>() as DWORD,
h_mod as *mut HMODULE,
size_of::<u32>() as u32,
&mut cb_needed,
LIST_MODULES_ALL,
)
Expand All @@ -380,8 +382,7 @@ fn get_command(handle: HANDLE) -> Option<String> {
return None;
}

let ret =
unsafe { GetModuleBaseNameW(handle, h_mod, exe_buf.as_mut_ptr(), MAX_PATH as DWORD + 1) };
let ret = unsafe { GetModuleBaseNameW(handle, h_mod, exe_buf.as_mut_ptr(), MAX_PATH + 1) };

let mut pos = 0;
for x in exe_buf.iter() {
Expand Down Expand Up @@ -599,9 +600,9 @@ fn get_name(psid: PSID) -> Option<(String, String)> {
let ret = LookupAccountSidW(
ptr::null::<u16>() as *mut u16,
psid,
name.as_mut_ptr() as *mut u16,
name.as_mut_ptr(),
&mut cc_name,
domainname.as_mut_ptr() as *mut u16,
domainname.as_mut_ptr(),
&mut cc_domainname,
&mut pe_use,
);
Expand Down
Loading