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

Add support for executing WMI methods #104

Merged
merged 7 commits into from
Dec 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ serde = { version = "1.0", features = ["derive"] }
futures = { version = "0.3" }
thiserror = "^2"
log = "0.4"
typeid = "1.0.2"
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved

[dev-dependencies]
async-std = { version = "1.10", features = ["attributes"] }
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,11 @@ mod datetime_time;
pub mod context;
pub mod de;
pub mod duration;
pub mod method;
pub mod query;
pub mod result_enumerator;
pub mod safearray;
pub mod ser;
pub mod utils;
pub mod variant;

Expand Down
198 changes: 198 additions & 0 deletions src/method.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
use std::collections::HashMap;

use serde::{de, Serialize};
use windows_core::{BSTR, HSTRING, VARIANT};

use crate::{
de::meta::struct_name_and_fields, result_enumerator::IWbemClassWrapper,
ser::variant_ser::VariantStructSerializer, WMIConnection, WMIError, WMIResult,
};

impl WMIConnection {
fn exec_method_native_wrapper(
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
&self,
method_class: impl AsRef<str>,
object_path: impl AsRef<str>,
method: impl AsRef<str>,
in_params: HashMap<String, VARIANT>,
) -> WMIResult<Option<IWbemClassWrapper>> {
let method_class = BSTR::from(method_class.as_ref());
let object_path = BSTR::from(object_path.as_ref());
let method = BSTR::from(method.as_ref());

unsafe {
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
let mut class_object = None;
self.svc.GetObject(
&method_class,
Default::default(),
&self.ctx.0,
Some(&mut class_object),
None,
)?;

match class_object {
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
Some(class) => {
let mut input_signature = None;
class.GetMethod(
&method,
Default::default(),
&mut input_signature,
std::ptr::null_mut(),
)?;
let object = match input_signature {
Some(input) => {
let inst = input.SpawnInstance(0)?;
for (wszname, value) in in_params {
inst.Put(&HSTRING::from(wszname), Default::default(), &value, 0)?;
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
}
Some(inst)
}
None => None,
};

let mut output = None;
self.svc.ExecMethod(
&object_path,
&method,
Default::default(),
&self.ctx.0,
object.as_ref(),
Some(&mut output),
None,
)?;

match output {
Some(wbem_class_obj) => Ok(Some(IWbemClassWrapper::new(wbem_class_obj))),
None => Ok(None),
}
}
None => Err(WMIError::ResultEmpty),
}
}
}

pub fn exec_class_method<MethodClass, In, Out>(
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
&self,
method: impl AsRef<str>,
in_params: In,
) -> WMIResult<Option<Out>>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be just WMIResult<Out>? The user can either set Out = (), or set it to something, so they should always know what's the right return type

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! In my implementation, I added the bound that if the function returns nothing, the only output type that will be accepted is the unit type. I think this is a reasonable compromise, but let me know if you think otherwise.

where
MethodClass: de::DeserializeOwned,
In: Serialize,
Out: de::DeserializeOwned,
{
let (method_class, _) = struct_name_and_fields::<MethodClass>()?;
self.exec_instance_method::<MethodClass, In, Out>(method, method_class, in_params)
}

pub fn exec_instance_method<MethodClass, In, Out>(
&self,
method: impl AsRef<str>,
object_path: impl AsRef<str>,
in_params: In,
) -> WMIResult<Option<Out>>
where
MethodClass: de::DeserializeOwned,
In: Serialize,
Out: de::DeserializeOwned,
{
let (method_class, _) = struct_name_and_fields::<MethodClass>()?;
let serializer = VariantStructSerializer::new();
match in_params.serialize(serializer) {
Ok(field_map) => {
let field_map: HashMap<String, VARIANT> = field_map
.into_iter()
.filter_map(|(k, v)| match TryInto::<VARIANT>::try_into(v).ok() {
Some(variant) => Some((k, variant)),
None => None,
})
.collect();
let output =
self.exec_method_native_wrapper(method_class, object_path, method, field_map);

match output {
Ok(wbem_class_obj) => match wbem_class_obj {
Some(wbem_class_obj) => Ok(Some(wbem_class_obj.into_desr()?)),
None => Ok(None),
},
Err(e) => Err(e),
}
}
Err(e) => Err(WMIError::ConvertVariantError(e.to_string())),
}
}
}

#[cfg(test)]
mod tests {
use crate::tests::fixtures::wmi_con;
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct Win32_Process {
__Path: String,
}

#[derive(Serialize)]
struct CreateParams {
CommandLine: String,
}

#[derive(Serialize)]
struct TerminateParams {}

#[derive(Deserialize)]
struct TerminateOutput {}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct CreateOutput {
ProcessId: u32,
}

#[test]
fn it_exec_class_method() {
let wmi_con = wmi_con();
let in_params = CreateParams {
CommandLine: "notepad.exe".to_string(),
};

let out = wmi_con
.exec_class_method::<Win32_Process, CreateParams, CreateOutput>("Create", in_params)
.unwrap()
.unwrap();

assert!(out.ProcessId != 0);
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
}

#[test]
fn it_exec_instance_method() {
Copy link
Owner

@ohadravid ohadravid Dec 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Running locally, this seems to be flaky for some reason:

failures:

---- method::tests::it_exec_class_method stdout ----
thread 'method::tests::it_exec_class_method' panicked at src\method.rs:162:14:
called `Result::unwrap()` on an `Err` value: SerdeError("invalid type: Option value, expected u32")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- method::tests::it_exec_instance_method stdout ----
thread 'method::tests::it_exec_instance_method' panicked at src\method.rs:177:14:
called `Result::unwrap()` on an `Err` value: SerdeError("invalid type: Option value, expected u32")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran it a few more times on my machine and was able to reproduce this. I'm not sure what's causing it, but the process create method is failing with the generic error code 8 ("unknown failure").

This seems to be happening totally unpredictably, so I don't believe it's tied to this implementation, but I haven't had the chance to test whether it occurs with WMI bindings in other languages. We could ignore the test, or rework it to use another WMI method instead.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On my machine, even the VBS example from https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/create-method-in-class-win32-process#examples fails randomly with 8/9/21.

But surpassingly, only for notepad.exe. Switching to powershell.exe seems to work consistently.

// Create notepad instance
let wmi_con = wmi_con();
let in_params = CreateParams {
CommandLine: "notepad.exe".to_string(),
};
let out = wmi_con
.exec_class_method::<Win32_Process, CreateParams, CreateOutput>("Create", in_params)
.unwrap()
.unwrap();

let process = wmi_con
.raw_query::<Win32_Process>(format!(
"SELECT * FROM Win32_Process WHERE ProcessId = {}",
out.ProcessId
))
.unwrap()
.into_iter()
.next()
.unwrap();

let _ = wmi_con
.exec_instance_method::<Win32_Process, TerminateParams, TerminateOutput>(
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
"Terminate",
process.__Path,
TerminateParams {},
)
.unwrap();
TechnoPorg marked this conversation as resolved.
Show resolved Hide resolved
}
}
1 change: 1 addition & 0 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod variant_ser;
Loading