Debian Codegraph @

third_party/rust/authenticator/src/transport/windows/winapi.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use std::io;
6 use std::mem;
7 use std::ptr;
8 use std::slice;
9
10 use std::ffi::OsString;
11 use std::os::windows::ffi::OsStringExt;
12
13 use crate::util::io_err;
14
15 extern crate libc;
16 extern crate winapi;
17
18 use winapi::shared::{guiddef, minwindef, ntdef, windef};
19 use winapi::shared::{hidclass, hidpi, hidusage};
20 use winapi::um::{handleapi, setupapi};
21
22 #[link(name = "setupapi")]
23 extern "system" {
24 fn SetupDiGetClassDevsW(
25 ClassGuid: *const guiddef::GUID,
26 Enumerator: ntdef::PCSTR,
27 hwndParent: windef::HWND,
28 flags: minwindef::DWORD,
29 ) -> setupapi::HDEVINFO;
30
31 fn SetupDiDestroyDeviceInfoList(DeviceInfoSet: setupapi::HDEVINFO) -> minwindef::BOOL;
32
33 fn SetupDiEnumDeviceInterfaces(
34 DeviceInfoSet: setupapi::HDEVINFO,
35 DeviceInfoData: setupapi::PSP_DEVINFO_DATA,
36 InterfaceClassGuid: *const guiddef::GUID,
37 MemberIndex: minwindef::DWORD,
38 DeviceInterfaceData: setupapi::PSP_DEVICE_INTERFACE_DATA,
39 ) -> minwindef::BOOL;
40
41 fn SetupDiGetDeviceInterfaceDetailW(
42 DeviceInfoSet: setupapi::HDEVINFO,
43 DeviceInterfaceData: setupapi::PSP_DEVICE_INTERFACE_DATA,
44 DeviceInterfaceDetailData: setupapi::PSP_DEVICE_INTERFACE_DETAIL_DATA_W,
45 DeviceInterfaceDetailDataSize: minwindef::DWORD,
46 RequiredSize: minwindef::PDWORD,
47 DeviceInfoData: setupapi::PSP_DEVINFO_DATA,
48 ) -> minwindef::BOOL;
49 }
50
51 #[link(name = "hid")]
52 extern "system" {
53 fn HidD_GetPreparsedData(
54 HidDeviceObject: ntdef::HANDLE,
55 PreparsedData: *mut hidpi::PHIDP_PREPARSED_DATA,
56 ) -> ntdef::BOOLEAN;
57
58 fn HidD_FreePreparsedData(PreparsedData: hidpi::PHIDP_PREPARSED_DATA) -> ntdef::BOOLEAN;
59
60 fn HidP_GetCaps(
61 PreparsedData: hidpi::PHIDP_PREPARSED_DATA,
62 Capabilities: hidpi::PHIDP_CAPS,
63 ) -> ntdef::NTSTATUS;
64 }
65
66 fn from_wide_ptr(ptr: *const u16, len: usize) -> String {
67 assert!(!ptr.is_null() && len % 2 == 0);
68 let slice = unsafe { slice::from_raw_parts(ptr, len / 2) };
69 OsString::from_wide(slice).to_string_lossy().into_owned()
70 }
71
72 pub struct DeviceInfoSet {
73 set: setupapi::HDEVINFO,
74 }
75
76 impl DeviceInfoSet {
77 pub fn new() -> io::Result<Self> {
78 let flags = setupapi::DIGCF_PRESENT | setupapi::DIGCF_DEVICEINTERFACE;
79 let set = unsafe {
80 SetupDiGetClassDevsW(
81 &hidclass::GUID_DEVINTERFACE_HID,
82 ptr::null_mut(),
83 ptr::null_mut(),
84 flags,
85 )
86 };
87 if set == handleapi::INVALID_HANDLE_VALUE {
88 return Err(io_err("SetupDiGetClassDevsW failed!"));
89 }
90
91 Ok(Self { set })
92 }
93
94 pub fn get(&self) -> setupapi::HDEVINFO {
95 self.set
96 }
97
98 pub fn devices(&self) -> DeviceInfoSetIter {
99 DeviceInfoSetIter::new(self)
100 }
101 }
102
103 impl Drop for DeviceInfoSet {
104 fn drop(&mut self) {
105 let _ = unsafe { SetupDiDestroyDeviceInfoList(self.set) };
106 }
107 }
108
109 pub struct DeviceInfoSetIter<'a> {
110 set: &'a DeviceInfoSet,
111 index: minwindef::DWORD,
112 }
113
114 impl<'a> DeviceInfoSetIter<'a> {
115 fn new(set: &'a DeviceInfoSet) -> Self {
116 Self { set, index: 0 }
117 }
118 }
119
120 impl<'a> Iterator for DeviceInfoSetIter<'a> {
121 type Item = String;
122
123 fn next(&mut self) -> Option<Self::Item> {
124 let mut device_interface_data =
125 mem::MaybeUninit::<setupapi::SP_DEVICE_INTERFACE_DATA>::zeroed();
126 unsafe {
127 (*device_interface_data.as_mut_ptr()).cbSize =
128 mem::size_of::<setupapi::SP_DEVICE_INTERFACE_DATA>() as minwindef::UINT;
129 }
130
131 let rv = unsafe {
132 SetupDiEnumDeviceInterfaces(
133 self.set.get(),
134 ptr::null_mut(),
135 &hidclass::GUID_DEVINTERFACE_HID,
136 self.index,
137 device_interface_data.as_mut_ptr(),
138 )
139 };
140 if rv == 0 {
141 return None; // We're past the last device index.
142 }
143
144 // Determine the size required to hold a detail struct.
145 let mut required_size = 0;
146 unsafe {
147 SetupDiGetDeviceInterfaceDetailW(
148 self.set.get(),
149 device_interface_data.as_mut_ptr(),
150 ptr::null_mut(),
151 required_size,
152 &mut required_size,
153 ptr::null_mut(),
154 )
155 };
156 if required_size == 0 {
157 return None; // An error occurred.
158 }
159
160 let detail = DeviceInterfaceDetailData::new(required_size as usize)?;
161 let rv = unsafe {
162 SetupDiGetDeviceInterfaceDetailW(
163 self.set.get(),
164 device_interface_data.as_mut_ptr(),
165 detail.get(),
166 required_size,
167 ptr::null_mut(),
168 ptr::null_mut(),
169 )
170 };
171 if rv == 0 {
172 return None; // An error occurred.
173 }
174
175 self.index += 1;
176 Some(detail.path())
177 }
178 }
179
180 struct DeviceInterfaceDetailData {
181 data: setupapi::PSP_DEVICE_INTERFACE_DETAIL_DATA_W,
182 path_len: usize,
183 }
184
185 impl DeviceInterfaceDetailData {
186 fn new(size: usize) -> Option<Self> {
187 let mut cb_size = mem::size_of::<setupapi::SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
188 if cfg!(target_pointer_width = "32") {
189 cb_size = 4 + 2; // 4-byte uint + default TCHAR size. size_of is inaccurate.
190 }
191
192 if size < cb_size {
193 warn!("DeviceInterfaceDetailData is too small. {}", size);
194 return None;
195 }
196
197 let data = unsafe { libc::malloc(size) as setupapi::PSP_DEVICE_INTERFACE_DETAIL_DATA_W };
198 if data.is_null() {
199 return None;
200 }
201
202 // Set total size of the structure.
203 unsafe { (*data).cbSize = cb_size as minwindef::UINT };
204
205 // Compute offset of `SP_DEVICE_INTERFACE_DETAIL_DATA_W.DevicePath`.
206 let offset = memoffset::offset_of!(setupapi::SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath);
207
208 Some(Self {
209 data,
210 path_len: size - offset,
211 })
212 }
213
214 fn get(&self) -> setupapi::PSP_DEVICE_INTERFACE_DETAIL_DATA_W {
215 self.data
216 }
217
218 fn path(&self) -> String {
219 unsafe { from_wide_ptr(ptr::addr_of!((*self.data).DevicePath[0]), self.path_len - 2) }
220 }
221 }
222
223 impl Drop for DeviceInterfaceDetailData {
224 fn drop(&mut self) {
225 unsafe { libc::free(self.data as *mut libc::c_void) };
226 }
227 }
228
229 pub struct DeviceCapabilities {
230 caps: hidpi::HIDP_CAPS,
231 }
232
233 impl DeviceCapabilities {
234 pub fn new(handle: ntdef::HANDLE) -> io::Result<Self> {
235 let mut preparsed_data = ptr::null_mut();
236 let rv = unsafe { HidD_GetPreparsedData(handle, &mut preparsed_data) };
237 if rv == 0 || preparsed_data.is_null() {
238 return Err(io_err("HidD_GetPreparsedData failed!"));
239 }
240
241 let mut caps = mem::MaybeUninit::<hidpi::HIDP_CAPS>::uninit();
242 unsafe {
243 let rv = HidP_GetCaps(preparsed_data, caps.as_mut_ptr());
244 HidD_FreePreparsedData(preparsed_data);
245
246 if rv != hidpi::HIDP_STATUS_SUCCESS {
247 return Err(io_err("HidP_GetCaps failed!"));
248 }
249
250 Ok(Self {
251 caps: caps.assume_init(),
252 })
253 }
254 }
255
256 pub fn usage(&self) -> hidusage::USAGE {
257 self.caps.Usage
258 }
259
260 pub fn usage_page(&self) -> hidusage::USAGE {
261 self.caps.UsagePage
262 }
263 }