Debian Codegraph @

src/platform/windows_winusb/enumeration.rs

raw symbols SCIP
1 use std::{
2 ffi::{OsStr, OsString},
3 io::ErrorKind,
4 };
5
6 use log::debug;
7 use windows_sys::Win32::Devices::{
8 Properties::{
9 DEVPKEY_Device_Address, DEVPKEY_Device_BusNumber, DEVPKEY_Device_BusReportedDeviceDesc,
10 DEVPKEY_Device_CompatibleIds, DEVPKEY_Device_HardwareIds, DEVPKEY_Device_InstanceId,
11 DEVPKEY_Device_Parent, DEVPKEY_Device_Service,
12 },
13 Usb::GUID_DEVINTERFACE_USB_DEVICE,
14 };
15
16 use crate::{
17 descriptors::{decode_string_descriptor, language_id::US_ENGLISH, DESCRIPTOR_TYPE_STRING},
18 DeviceInfo, Error, InterfaceInfo,
19 };
20
21 use super::{
22 cfgmgr32::{self, get_device_interface_property, DevInst},
23 hub::HubPort,
24 util::WCString,
25 };
26
27 pub fn list_devices() -> Result<impl Iterator<Item = DeviceInfo>, Error> {
28 let devs: Vec<DeviceInfo> = cfgmgr32::list_interfaces(GUID_DEVINTERFACE_USB_DEVICE, None)
29 .iter()
30 .flat_map(|i| get_device_interface_property::<WCString>(i, DEVPKEY_Device_InstanceId))
31 .flat_map(|d| DevInst::from_instance_id(&d))
32 .flat_map(probe_device)
33 .collect();
34 Ok(devs.into_iter())
35 }
36
37 pub fn probe_device(devinst: DevInst) -> Option<DeviceInfo> {
38 let instance_id = devinst.get_property::<OsString>(DEVPKEY_Device_InstanceId)?;
39 debug!("Probing device {instance_id:?}");
40
41 let parent_instance_id = devinst.get_property::<OsString>(DEVPKEY_Device_Parent)?;
42 let bus_number = devinst.get_property::<u32>(DEVPKEY_Device_BusNumber)?;
43 let port_number = devinst.get_property::<u32>(DEVPKEY_Device_Address)?;
44
45 let hub_port = HubPort::by_child_devinst(devinst).ok()?;
46 let info = hub_port.get_info().ok()?;
47
48 let product_string = devinst
49 .get_property::<OsString>(DEVPKEY_Device_BusReportedDeviceDesc)
50 .and_then(|s| s.into_string().ok());
51
52 let serial_number = if info.device_desc.iSerialNumber != 0 {
53 // Experimentally confirmed, the string descriptor is cached and this does
54 // not perform IO. However, the language ID list is not cached, so we
55 // have to assume 0x0409 (which will be right 99% of the time).
56 hub_port
57 .get_descriptor(
58 DESCRIPTOR_TYPE_STRING,
59 info.device_desc.iSerialNumber,
60 US_ENGLISH,
61 )
62 .ok()
63 .and_then(|data| decode_string_descriptor(&data).ok())
64 } else {
65 None
66 };
67
68 let driver = devinst
69 .get_property::<OsString>(DEVPKEY_Device_Service)
70 .and_then(|s| s.into_string().ok())
71 .unwrap_or_default();
72
73 let mut interfaces = if driver.eq_ignore_ascii_case("usbccgp") {
74 devinst
75 .children()
76 .flat_map(|intf| {
77 let interface_number = get_interface_number(intf)?;
78 let (class, subclass, protocol) = intf
79 .get_property::<Vec<OsString>>(DEVPKEY_Device_CompatibleIds)?
80 .iter()
81 .find_map(|s| parse_compatible_id(s))?;
82 let interface_string = intf
83 .get_property::<OsString>(DEVPKEY_Device_BusReportedDeviceDesc)
84 .and_then(|s| s.into_string().ok());
85
86 Some(InterfaceInfo {
87 interface_number,
88 class,
89 subclass,
90 protocol,
91 interface_string,
92 })
93 })
94 .collect()
95 } else {
96 Vec::new()
97 };
98
99 interfaces.sort_unstable_by_key(|i| i.interface_number);
100
101 Some(DeviceInfo {
102 instance_id,
103 parent_instance_id,
104 devinst,
105 port_number,
106 driver: Some(driver).filter(|s| !s.is_empty()),
107 bus_number: bus_number as u8,
108 device_address: info.address,
109 vendor_id: info.device_desc.idVendor,
110 product_id: info.device_desc.idProduct,
111 device_version: info.device_desc.bcdDevice,
112 class: info.device_desc.bDeviceClass,
113 subclass: info.device_desc.bDeviceSubClass,
114 protocol: info.device_desc.bDeviceProtocol,
115 speed: info.speed,
116 manufacturer_string: None,
117 product_string,
118 serial_number,
119 interfaces,
120 })
121 }
122
123 /// Find the path to open for an interface of a device
124 ///
125 /// If the whole device is bound to WinUSB, it can be opened directly. For a
126 /// composite device, USB interfaces are represented by child device nodes.
127 pub(crate) fn find_device_interface_path(dev: DevInst, intf: u8) -> Result<WCString, Error> {
128 let driver = dev
129 .get_property::<OsString>(DEVPKEY_Device_Service)
130 .and_then(|s| s.into_string().ok())
131 .unwrap_or_default();
132
133 if driver.eq_ignore_ascii_case("usbccgp") {
134 let child = dev
135 .children()
136 .find(|i| get_interface_number(*i) == Some(intf))
137 .ok_or_else(|| Error::new(ErrorKind::NotFound, "Interface not found"))?;
138
139 let Some(driver) = child.get_property::<OsString>(DEVPKEY_Device_Service) else {
140 return Err(Error::new(
141 ErrorKind::Unsupported,
142 "Could not determine driver for interface",
143 ));
144 };
145
146 if !driver.eq_ignore_ascii_case("winusb") {
147 return Err(Error::new(
148 ErrorKind::Unsupported,
149 format!("Interface driver is {driver:?}, not WinUSB"),
150 ));
151 }
152
153 let reg_key = child.registry_key().unwrap();
154 let guid = match reg_key.query_value_guid("DeviceInterfaceGUIDs") {
155 Ok(s) => s,
156 Err(e) => match reg_key.query_value_guid("DeviceInterfaceGUID") {
157 Ok(s) => s,
158 Err(f) => {
159 if e.kind() == f.kind() {
160 debug!("Failed to get DeviceInterfaceGUID or DeviceInterfaceGUIDs from registry: {e}");
161 } else {
162 debug!("Failed to get DeviceInterfaceGUID or DeviceInterfaceGUIDs from registry: {e}, {f}");
163 }
164 return Err(Error::new(
165 ErrorKind::Unsupported,
166 "Could not find DeviceInterfaceGUIDs in registry. WinUSB driver may not be correctly installed for this interface."
167 ));
168 }
169 },
170 };
171
172 let paths = child.interfaces(guid);
173 let Some(path) = paths.iter().next() else {
174 return Err(Error::new(
175 ErrorKind::Other,
176 "Failed to find device path for WinUSB interface",
177 ));
178 };
179
180 Ok(path.to_owned())
181 } else if driver.eq_ignore_ascii_case("winusb") {
182 let paths = dev.interfaces(GUID_DEVINTERFACE_USB_DEVICE);
183
184 let Some(path) = paths.iter().next() else {
185 return Err(Error::new(
186 ErrorKind::Other,
187 "Failed to find device path for WinUSB device",
188 ));
189 };
190
191 Ok(path.to_owned())
192 } else {
193 return Err(Error::new(
194 ErrorKind::Unsupported,
195 format!("Device driver is {driver:?}, not WinUSB"),
196 ));
197 }
198 }
199
200 fn get_interface_number(intf_dev: DevInst) -> Option<u8> {
201 let hw_ids = intf_dev.get_property::<Vec<OsString>>(DEVPKEY_Device_HardwareIds);
202 hw_ids
203 .as_deref()
204 .unwrap_or_default()
205 .iter()
206 .find_map(|id| parse_hardware_id(id))
207 .or_else(|| {
208 debug!("Failed to parse interface number in hardware IDs: {hw_ids:?}");
209 None
210 })
211 }
212
213 /// Parse interface number from a Hardware ID value
214 fn parse_hardware_id(s: &OsStr) -> Option<u8> {
215 let s = s.to_str()?;
216 let s = s.rsplit_once("&MI_")?.1;
217 u8::from_str_radix(s.get(0..2)?, 16).ok()
218 }
219
220 #[test]
221 fn test_parse_hardware_id() {
222 assert_eq!(parse_hardware_id(OsStr::new("")), None);
223 assert_eq!(
224 parse_hardware_id(OsStr::new("USB\\VID_1234&PID_5678&MI_0A")),
225 Some(10)
226 );
227 assert_eq!(
228 parse_hardware_id(OsStr::new("USB\\VID_9999&PID_AAAA&REV_0101&MI_01")),
229 Some(1)
230 );
231 }
232
233 /// Parse class, subclass, protocol from a Compatible ID value
234 fn parse_compatible_id(s: &OsStr) -> Option<(u8, u8, u8)> {
235 let s = s.to_str()?;
236 let s = s.strip_prefix("USB\\Class_")?;
237 let class = u8::from_str_radix(s.get(0..2)?, 16).ok()?;
238 let s = s.get(2..)?.strip_prefix("&SubClass_")?;
239 let subclass = u8::from_str_radix(s.get(0..2)?, 16).ok()?;
240 let s = s.get(2..)?.strip_prefix("&Prot_")?;
241 let protocol = u8::from_str_radix(s.get(0..2)?, 16).ok()?;
242 Some((class, subclass, protocol))
243 }
244
245 #[test]
246 fn test_parse_compatible_id() {
247 assert_eq!(parse_compatible_id(OsStr::new("")), None);
248 assert_eq!(parse_compatible_id(OsStr::new("USB\\Class_03")), None);
249 assert_eq!(
250 parse_compatible_id(OsStr::new("USB\\Class_03&SubClass_11&Prot_22")),
251 Some((3, 17, 34))
252 );
253 }