| 1 |
use std::{ |
| 2 |
ffi::c_void, |
| 3 |
io::{self, ErrorKind}, |
| 4 |
mem::size_of_val, |
| 5 |
os::windows::prelude::OwnedHandle, |
| 6 |
ptr::null_mut, |
| 7 |
sync::Arc, |
| 8 |
time::Duration, |
| 9 |
}; |
| 10 |
|
| 11 |
use log::{debug, error, warn}; |
| 12 |
use windows_sys::Win32::{ |
| 13 |
Devices::Usb::{ |
| 14 |
WinUsb_ControlTransfer, WinUsb_Free, WinUsb_Initialize, WinUsb_ResetPipe, |
| 15 |
WinUsb_SetCurrentAlternateSetting, WinUsb_SetPipePolicy, PIPE_TRANSFER_TIMEOUT, |
| 16 |
WINUSB_INTERFACE_HANDLE, WINUSB_SETUP_PACKET, |
| 17 |
}, |
| 18 |
Foundation::{GetLastError, FALSE, TRUE}, |
| 19 |
}; |
| 20 |
|
| 21 |
use crate::{ |
| 22 |
descriptors::{validate_config_descriptor, DESCRIPTOR_TYPE_CONFIGURATION}, |
| 23 |
transfer::{Control, Direction, EndpointType, Recipient, TransferError, TransferHandle}, |
| 24 |
DeviceInfo, Error, |
| 25 |
}; |
| 26 |
|
| 27 |
use super::{ |
| 28 |
enumeration::find_device_interface_path, |
| 29 |
hub::HubPort, |
| 30 |
util::{create_file, raw_handle}, |
| 31 |
DevInst, |
| 32 |
}; |
| 33 |
|
| 34 |
pub(crate) struct WindowsDevice { |
| 35 |
config_descriptors: Vec<Vec<u8>>, |
| 36 |
active_config: u8, |
| 37 |
devinst: DevInst, |
| 38 |
} |
| 39 |
|
| 40 |
impl WindowsDevice { |
| 41 |
pub(crate) fn from_device_info(d: &DeviceInfo) -> Result<Arc<WindowsDevice>, Error> { |
| 42 |
debug!("Creating device for {:?}", d.instance_id); |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
let hub_port = HubPort::by_child_devinst(d.devinst)?; |
| 49 |
let connection_info = hub_port.get_info()?; |
| 50 |
let num_configurations = connection_info.device_desc.bNumConfigurations; |
| 51 |
|
| 52 |
let config_descriptors = (0..num_configurations) |
| 53 |
.flat_map(|i| { |
| 54 |
let res = hub_port.get_descriptor(DESCRIPTOR_TYPE_CONFIGURATION, i, 0); |
| 55 |
match res { |
| 56 |
Ok(v) => validate_config_descriptor(&v[..]).map(|_| v), |
| 57 |
Err(e) => { |
| 58 |
error!("Failed to read config descriptor {}: {}", i, e); |
| 59 |
None |
| 60 |
} |
| 61 |
} |
| 62 |
}) |
| 63 |
.collect(); |
| 64 |
|
| 65 |
Ok(Arc::new(WindowsDevice { |
| 66 |
config_descriptors, |
| 67 |
active_config: connection_info.active_config, |
| 68 |
devinst: d.devinst, |
| 69 |
})) |
| 70 |
} |
| 71 |
|
| 72 |
pub(crate) fn active_configuration_value(&self) -> u8 { |
| 73 |
self.active_config |
| 74 |
} |
| 75 |
|
| 76 |
pub(crate) fn configuration_descriptors(&self) -> impl Iterator<Item = &[u8]> { |
| 77 |
self.config_descriptors.iter().map(|d| &d[..]) |
| 78 |
} |
| 79 |
|
| 80 |
pub(crate) fn set_configuration(&self, _configuration: u8) -> Result<(), Error> { |
| 81 |
Err(io::Error::new( |
| 82 |
ErrorKind::Unsupported, |
| 83 |
"set_configuration not supported by WinUSB", |
| 84 |
)) |
| 85 |
} |
| 86 |
|
| 87 |
pub(crate) fn get_descriptor( |
| 88 |
&self, |
| 89 |
desc_type: u8, |
| 90 |
desc_index: u8, |
| 91 |
language_id: u16, |
| 92 |
) -> Result<Vec<u8>, Error> { |
| 93 |
HubPort::by_child_devinst(self.devinst)?.get_descriptor(desc_type, desc_index, language_id) |
| 94 |
} |
| 95 |
|
| 96 |
pub(crate) fn reset(&self) -> Result<(), Error> { |
| 97 |
Err(io::Error::new( |
| 98 |
ErrorKind::Unsupported, |
| 99 |
"reset not supported by WinUSB", |
| 100 |
)) |
| 101 |
} |
| 102 |
|
| 103 |
pub(crate) fn claim_interface( |
| 104 |
self: &Arc<Self>, |
| 105 |
interface_number: u8, |
| 106 |
) -> Result<Arc<WindowsInterface>, Error> { |
| 107 |
let path = find_device_interface_path(self.devinst, interface_number)?; |
| 108 |
|
| 109 |
log::debug!( |
| 110 |
"Claiming device {:?} interface {interface_number} with interface path `{path}`", |
| 111 |
self.devinst |
| 112 |
); |
| 113 |
|
| 114 |
let handle = create_file(&path)?; |
| 115 |
|
| 116 |
super::events::register(&handle)?; |
| 117 |
|
| 118 |
let winusb_handle = unsafe { |
| 119 |
let mut h = 0; |
| 120 |
if WinUsb_Initialize(raw_handle(&handle), &mut h) == FALSE { |
| 121 |
error!("WinUsb_Initialize failed: {:?}", io::Error::last_os_error()); |
| 122 |
return Err(io::Error::last_os_error()); |
| 123 |
} |
| 124 |
h |
| 125 |
}; |
| 126 |
|
| 127 |
Ok(Arc::new(WindowsInterface { |
| 128 |
handle, |
| 129 |
device: self.clone(), |
| 130 |
interface_number, |
| 131 |
winusb_handle, |
| 132 |
})) |
| 133 |
} |
| 134 |
|
| 135 |
pub(crate) fn detach_and_claim_interface( |
| 136 |
self: &Arc<Self>, |
| 137 |
interface: u8, |
| 138 |
) -> Result<Arc<WindowsInterface>, Error> { |
| 139 |
self.claim_interface(interface) |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
pub(crate) struct WindowsInterface { |
| 144 |
pub(crate) handle: OwnedHandle, |
| 145 |
pub(crate) device: Arc<WindowsDevice>, |
| 146 |
pub(crate) interface_number: u8, |
| 147 |
pub(crate) winusb_handle: WINUSB_INTERFACE_HANDLE, |
| 148 |
} |
| 149 |
|
| 150 |
impl WindowsInterface { |
| 151 |
pub(crate) fn make_transfer( |
| 152 |
self: &Arc<Self>, |
| 153 |
endpoint: u8, |
| 154 |
ep_type: EndpointType, |
| 155 |
) -> TransferHandle<super::TransferData> { |
| 156 |
TransferHandle::new(super::TransferData::new(self.clone(), endpoint, ep_type)) |
| 157 |
} |
| 158 |
|
| 159 |
|
| 160 |
unsafe fn control_blocking( |
| 161 |
&self, |
| 162 |
direction: Direction, |
| 163 |
control: Control, |
| 164 |
data: *mut u8, |
| 165 |
len: usize, |
| 166 |
timeout: Duration, |
| 167 |
) -> Result<usize, TransferError> { |
| 168 |
debug!("Blocking control {direction:?}, {len} bytes"); |
| 169 |
|
| 170 |
if control.recipient == Recipient::Interface && control.index as u8 != self.interface_number |
| 171 |
{ |
| 172 |
warn!("WinUSB sends interface number instead of passed `index` when performing a control transfer with `Recipient::Interface`"); |
| 173 |
} |
| 174 |
|
| 175 |
let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32; |
| 176 |
let r = WinUsb_SetPipePolicy( |
| 177 |
self.winusb_handle, |
| 178 |
0, |
| 179 |
PIPE_TRANSFER_TIMEOUT, |
| 180 |
size_of_val(&timeout_ms) as u32, |
| 181 |
&timeout_ms as *const u32 as *const c_void, |
| 182 |
); |
| 183 |
|
| 184 |
if r != TRUE { |
| 185 |
error!( |
| 186 |
"WinUsb_SetPipePolicy PIPE_TRANSFER_TIMEOUT failed: {}", |
| 187 |
io::Error::last_os_error() |
| 188 |
); |
| 189 |
} |
| 190 |
|
| 191 |
let pkt = WINUSB_SETUP_PACKET { |
| 192 |
RequestType: control.request_type(direction), |
| 193 |
Request: control.request, |
| 194 |
Value: control.value, |
| 195 |
Index: control.index, |
| 196 |
Length: len.try_into().expect("request size too large"), |
| 197 |
}; |
| 198 |
|
| 199 |
let mut actual_len = 0; |
| 200 |
|
| 201 |
let r = WinUsb_ControlTransfer( |
| 202 |
self.winusb_handle, |
| 203 |
pkt, |
| 204 |
data, |
| 205 |
len.try_into().expect("request size too large"), |
| 206 |
&mut actual_len, |
| 207 |
null_mut(), |
| 208 |
); |
| 209 |
|
| 210 |
if r == TRUE { |
| 211 |
Ok(actual_len as usize) |
| 212 |
} else { |
| 213 |
error!( |
| 214 |
"WinUsb_ControlTransfer failed: {}", |
| 215 |
io::Error::last_os_error() |
| 216 |
); |
| 217 |
Err(super::transfer::map_error(GetLastError())) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
pub fn control_in_blocking( |
| 222 |
&self, |
| 223 |
control: Control, |
| 224 |
data: &mut [u8], |
| 225 |
timeout: Duration, |
| 226 |
) -> Result<usize, TransferError> { |
| 227 |
unsafe { |
| 228 |
self.control_blocking( |
| 229 |
Direction::In, |
| 230 |
control, |
| 231 |
data.as_mut_ptr(), |
| 232 |
data.len(), |
| 233 |
timeout, |
| 234 |
) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
pub fn control_out_blocking( |
| 239 |
&self, |
| 240 |
control: Control, |
| 241 |
data: &[u8], |
| 242 |
timeout: Duration, |
| 243 |
) -> Result<usize, TransferError> { |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
let mut buf = [0; 4096]; |
| 250 |
let Some(buf) = buf.get_mut(..data.len()) else { |
| 251 |
error!( |
| 252 |
"Control transfer length {} exceeds limit of 4096", |
| 253 |
data.len() |
| 254 |
); |
| 255 |
return Err(TransferError::Unknown); |
| 256 |
}; |
| 257 |
buf.copy_from_slice(data); |
| 258 |
|
| 259 |
unsafe { |
| 260 |
self.control_blocking( |
| 261 |
Direction::Out, |
| 262 |
control, |
| 263 |
buf.as_mut_ptr(), |
| 264 |
buf.len(), |
| 265 |
timeout, |
| 266 |
) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
pub fn set_alt_setting(&self, alt_setting: u8) -> Result<(), Error> { |
| 271 |
unsafe { |
| 272 |
let r = WinUsb_SetCurrentAlternateSetting(self.winusb_handle, alt_setting.into()); |
| 273 |
if r == TRUE { |
| 274 |
Ok(()) |
| 275 |
} else { |
| 276 |
Err(io::Error::last_os_error()) |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
pub fn clear_halt(&self, endpoint: u8) -> Result<(), Error> { |
| 282 |
debug!("Clear halt, endpoint {endpoint:02x}"); |
| 283 |
unsafe { |
| 284 |
let r = WinUsb_ResetPipe(self.winusb_handle, endpoint); |
| 285 |
if r == TRUE { |
| 286 |
Ok(()) |
| 287 |
} else { |
| 288 |
Err(io::Error::last_os_error()) |
| 289 |
} |
| 290 |
} |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
impl Drop for WindowsInterface { |
| 295 |
fn drop(&mut self) { |
| 296 |
unsafe { |
| 297 |
WinUsb_Free(self.winusb_handle); |
| 298 |
} |
| 299 |
} |
| 300 |
} |