Skip to main content

windows_wmi_com/
wmi.rs

1use crate::error::{Error, Result};
2use crate::row::Row;
3use crate::FromWbem;
4
5#[cfg(windows)]
6use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
7#[cfg(windows)]
8use windows::Win32::System::Com::{
9    CoCreateInstance, CoInitializeEx, CoSetProxyBlanket, CoUninitialize, CLSCTX_INPROC_SERVER,
10    COINIT_MULTITHREADED, EOAC_NONE, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE,
11};
12#[cfg(windows)]
13use windows::Win32::System::Rpc::{RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE};
14#[cfg(windows)]
15use windows::Win32::System::Wmi::{
16    IEnumWbemClassObject, IWbemClassObject, IWbemLocator, IWbemServices, WbemLocator,
17    WBEM_FLAG_FORWARD_ONLY, WBEM_FLAG_RETURN_IMMEDIATELY, WBEM_INFINITE,
18};
19#[cfg(windows)]
20use windows_core::{BSTR, PCWSTR, VARIANT};
21
22/// A live COM WMI session bound to a single namespace on the local host.
23///
24/// Threading: `connect_local` forces the MTA. The instance is deliberately
25/// `!Send` — the underlying COM proxies are apartment-scoped and must be
26/// touched from the thread that initialized COM.
27///
28/// Drop order matters here: Rust drops fields in declaration order, so the
29/// COM interfaces (`services`, `_locator`) release *first*, and only then
30/// does [`ComGuard`] run `CoUninitialize`. Calling `Release` on a live
31/// proxy after `CoUninitialize` is undefined behavior — an easy way to
32/// earn an `0xc0000005` in a test binary.
33pub struct Wmi {
34    #[cfg(windows)]
35    services: IWbemServices,
36    #[cfg(windows)]
37    _locator: IWbemLocator,
38    #[cfg(windows)]
39    _com: ComGuard,
40
41    // Force !Send / !Sync — COM proxies are per-apartment.
42    _not_send: std::marker::PhantomData<*const ()>,
43}
44
45/// Owns the `CoInitializeEx` reservation for the lifetime of a [`Wmi`].
46/// The `initialized` flag distinguishes "we called `CoInitializeEx` and
47/// therefore must uninitialize" from "the thread was already in an
48/// incompatible apartment (RPC_E_CHANGED_MODE) and we rode along".
49#[cfg(windows)]
50struct ComGuard {
51    initialized: bool,
52}
53
54#[cfg(windows)]
55impl Drop for ComGuard {
56    fn drop(&mut self) {
57        if self.initialized {
58            unsafe { CoUninitialize() };
59        }
60    }
61}
62
63#[cfg(windows)]
64impl Wmi {
65    /// Connect to `\\.\root\<namespace>` in-process. `namespace` is typically
66    /// `"ROOT\\CIMV2"`.
67    pub fn connect_local(namespace: &str) -> Result<Self> {
68        unsafe {
69            let hr = CoInitializeEx(None, COINIT_MULTITHREADED);
70            // S_OK (0) and S_FALSE (1) both mean "you initialized COM now".
71            // RPC_E_CHANGED_MODE means an STA was set up earlier on this
72            // thread by someone else — we accept it and don't own the init.
73            let com_initialized = if hr.0 == 0 || hr.0 == 1 {
74                true
75            } else if hr == RPC_E_CHANGED_MODE {
76                false
77            } else {
78                return Err(Error::CoInit(hr.0));
79            };
80
81            let locator: IWbemLocator = CoCreateInstance(&WbemLocator, None, CLSCTX_INPROC_SERVER)?;
82
83            let resource: BSTR = format!("\\\\.\\{}", namespace).into();
84            let empty: BSTR = BSTR::new();
85            let services: IWbemServices =
86                locator.ConnectServer(&resource, &empty, &empty, &empty, 0, &empty, None)?;
87
88            // Per-proxy security — the local WMI service enforces impersonation.
89            // Skipping this yields E_ACCESSDENIED on the first ExecQuery.
90            CoSetProxyBlanket(
91                &services,
92                RPC_C_AUTHN_WINNT,
93                RPC_C_AUTHZ_NONE,
94                PCWSTR::null(),
95                RPC_C_AUTHN_LEVEL_CALL,
96                RPC_C_IMP_LEVEL_IMPERSONATE,
97                None,
98                EOAC_NONE,
99            )?;
100
101            Ok(Self {
102                services,
103                _locator: locator,
104                _com: ComGuard {
105                    initialized: com_initialized,
106                },
107                _not_send: std::marker::PhantomData,
108            })
109        }
110    }
111
112    /// Run a WQL query and return an iterator of untyped rows.
113    pub fn query_raw(&self, wql: &str) -> Result<Box<dyn Iterator<Item = Result<Row>>>> {
114        unsafe {
115            let language: BSTR = "WQL".into();
116            let query: BSTR = wql.into();
117            let flags = WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY;
118            let enumerator: IEnumWbemClassObject =
119                self.services.ExecQuery(&language, &query, flags, None)?;
120
121            Ok(Box::new(QueryIter { enumerator }))
122        }
123    }
124
125    /// Run a WQL query and map each row through `T: FromWbem`.
126    pub fn query<T>(&self, wql: &str) -> Result<Box<dyn Iterator<Item = Result<T>>>>
127    where
128        T: FromWbem + 'static,
129    {
130        let raw = self.query_raw(wql)?;
131        Ok(Box::new(raw.map(|r| r.and_then(|row| T::from_wbem(&row)))))
132    }
133}
134
135// Drop is intentionally NOT implemented on `Wmi` — see the doc comment on
136// the struct. Field-drop order + `ComGuard`'s Drop sequences uninit correctly.
137
138// ---- non-Windows stubs so the crate at least compiles / documents on other OSes.
139// Everything here returns an error immediately — this crate is Windows-only in practice.
140#[cfg(not(windows))]
141impl Wmi {
142    pub fn connect_local(_namespace: &str) -> Result<Self> {
143        Err(Error::Hr {
144            context: "windows-wmi-com is Windows-only",
145            hr: 0,
146        })
147    }
148
149    pub fn query_raw(&self, _wql: &str) -> Result<Box<dyn Iterator<Item = Result<Row>>>> {
150        Err(Error::Hr {
151            context: "windows-wmi-com is Windows-only",
152            hr: 0,
153        })
154    }
155
156    pub fn query<T>(&self, _wql: &str) -> Result<Box<dyn Iterator<Item = Result<T>>>>
157    where
158        T: FromWbem + 'static,
159    {
160        Err(Error::Hr {
161            context: "windows-wmi-com is Windows-only",
162            hr: 0,
163        })
164    }
165}
166
167// ---------------------------------------------------------------------------
168// Enumerator wrapper
169// ---------------------------------------------------------------------------
170
171#[cfg(windows)]
172struct QueryIter {
173    enumerator: IEnumWbemClassObject,
174}
175
176#[cfg(windows)]
177impl Iterator for QueryIter {
178    type Item = Result<Row>;
179
180    fn next(&mut self) -> Option<Self::Item> {
181        unsafe {
182            let mut obj: [Option<IWbemClassObject>; 1] = [None];
183            let mut returned: u32 = 0;
184            let hr = self
185                .enumerator
186                .Next(WBEM_INFINITE as i32, &mut obj, &mut returned);
187            if hr.is_err() {
188                return Some(Err(Error::Hr {
189                    context: "IEnumWbemClassObject::Next",
190                    hr: hr.0,
191                }));
192            }
193            if returned == 0 {
194                return None;
195            }
196            let object = match obj[0].take() {
197                Some(o) => o,
198                None => return None,
199            };
200            Some(row_from_object(&object))
201        }
202    }
203}
204
205#[cfg(windows)]
206unsafe fn row_from_object(obj: &IWbemClassObject) -> Result<Row> {
207    let mut row = Row::new();
208
209    obj.BeginEnumeration(0)?;
210    loop {
211        let mut name = BSTR::new();
212        let mut val = VARIANT::default();
213        let mut vtype: i32 = 0;
214        let mut flavor: i32 = 0;
215        // windows-rs collapses WBEM_S_NO_MORE_DATA (0x40005, a *success* HRESULT)
216        // into Ok(()) — no way to tell it apart from a normal Ok. We detect
217        // end-of-enumeration via the returned BSTR: WMI leaves it empty when
218        // there are no more properties to yield.
219        if let Err(e) = obj.Next(0, &mut name, &mut val, &mut vtype, &mut flavor) {
220            let _ = obj.EndEnumeration();
221            return Err(Error::Windows(e));
222        }
223        if name.is_empty() {
224            break;
225        }
226
227        let key = name.to_string();
228        let value = crate::value::convert::from_variant(&val);
229        row.insert(key, value);
230    }
231    obj.EndEnumeration()?;
232    Ok(row)
233}