| 1 | use std::io::{ErrorKind, Seek}; |
| 2 | use std::{ffi::c_void, time::Duration}; |
| 3 | use std::{ |
| 4 | fs::File, |
| 5 | io::Read, |
| 6 | mem::ManuallyDrop, |
| 7 | path::PathBuf, |
| 8 | sync::{ |
| 9 | atomic::{AtomicU8, Ordering}, |
| 10 | Arc, |
| 11 | }, |
| 12 | }; |
| 13 | |
| 14 | use log::{debug, error, warn}; |
| 15 | use rustix::event::epoll; |
| 16 | use rustix::fd::AsFd; |
| 17 | use rustix::{ |
| 18 | fd::{AsRawFd, FromRawFd, OwnedFd}, |
| 19 | fs::{Mode, OFlags}, |
| 20 | io::Errno, |
| 21 | }; |
| 22 | |
| 23 | use super::{ |
| 24 | errno_to_transfer_error, events, |
| 25 | usbfs::{self, Urb}, |
| 26 | SysfsPath, |
| 27 | }; |
| 28 | use crate::platform::linux_usbfs::events::Watch; |
| 29 | use crate::{ |
| 30 | descriptors::{parse_concatenated_config_descriptors, Configuration, DESCRIPTOR_LEN_DEVICE}, |
| 31 | transfer::{ |
| 32 | notify_completion, Control, ControlType, Direction, EndpointType, Recipient, TransferError, |
| 33 | TransferHandle, |
| 34 | }, |
| 35 | DeviceInfo, Error, |
| 36 | }; |
| 37 | |
| 38 | pub(crate) struct LinuxDevice { |
| 39 | fd: OwnedFd, |
| 40 | events_id: usize, |
| 41 | |
| 42 | /// Read from the fd, consists of device descriptor followed by configuration descriptors |
| 43 | descriptors: Vec<u8>, |
| 44 | |
| 45 | sysfs: Option<SysfsPath>, |
| 46 | active_config: AtomicU8, |
| 47 | } |
| 48 | |
| 49 | impl LinuxDevice { |
| 50 | pub(crate) fn from_device_info(d: &DeviceInfo) -> Result<Arc<LinuxDevice>, Error> { |
| 51 | let busnum = d.bus_number(); |
| 52 | let devnum = d.device_address(); |
| 53 | let active_config = d.path.read_attr("bConfigurationValue")?; |
| 54 | |
| 55 | let path = PathBuf::from(format!("/dev/bus/usb/{busnum:03}/{devnum:03}")); |
| 56 | debug!("Opening usbfs device {}", path.display()); |
| 57 | let fd = rustix::fs::open(path, OFlags::RDWR | OFlags::CLOEXEC, Mode::empty())?; |
| 58 | |
| 59 | let inner = Self::create_inner(fd, Some(d.path.clone()), Some(active_config)); |
| 60 | if inner.is_ok() { |
| 61 | debug!("Opened device bus={busnum} addr={devnum}",); |
| 62 | } |
| 63 | inner |
| 64 | } |
| 65 | |
| 66 | pub(crate) fn from_fd(fd: OwnedFd) -> Result<Arc<LinuxDevice>, Error> { |
| 67 | debug!("Wrapping fd {} as usbfs device", fd.as_raw_fd()); |
| 68 | |
| 69 | Self::create_inner(fd, None, None) |
| 70 | } |
| 71 | |
| 72 | pub(crate) fn create_inner( |
| 73 | fd: OwnedFd, |
| 74 | sysfs: Option<SysfsPath>, |
| 75 | active_config: Option<u8>, |
| 76 | ) -> Result<Arc<LinuxDevice>, Error> { |
| 77 | let descriptors = { |
| 78 | let mut file = unsafe { ManuallyDrop::new(File::from_raw_fd(fd.as_raw_fd())) }; |
| 79 | // NOTE: Seek required on android |
| 80 | file.seek(std::io::SeekFrom::Start(0))?; |
| 81 | let mut buf = Vec::new(); |
| 82 | file.read_to_end(&mut buf)?; |
| 83 | buf |
| 84 | }; |
| 85 | |
| 86 | let active_config = if let Some(active_config) = active_config { |
| 87 | active_config |
| 88 | } else { |
| 89 | Self::get_config(&descriptors, &fd)? |
| 90 | }; |
| 91 | |
| 92 | // because there's no Arc::try_new_cyclic |
| 93 | let mut events_err = None; |
| 94 | let arc = Arc::new_cyclic(|weak| { |
| 95 | let res = events::register( |
| 96 | fd.as_fd(), |
| 97 | Watch::Device(weak.clone()), |
| 98 | epoll::EventFlags::OUT, |
| 99 | ); |
| 100 | let events_id = *res.as_ref().unwrap_or(&usize::MAX); |
| 101 | events_err = res.err(); |
| 102 | if events_err.is_none() { |
| 103 | debug!("Opened device fd={} with id {}", fd.as_raw_fd(), events_id,); |
| 104 | } |
| 105 | LinuxDevice { |
| 106 | fd, |
| 107 | events_id, |
| 108 | descriptors, |
| 109 | sysfs, |
| 110 | active_config: AtomicU8::new(active_config), |
| 111 | } |
| 112 | }); |
| 113 | |
| 114 | if let Some(err) = events_err { |
| 115 | error!("Failed to initialize event loop: {err}"); |
| 116 | Err(err) |
| 117 | } else { |
| 118 | Ok(arc) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn handle_events(&self) { |
| 123 | debug!("Handling events for device {}", self.events_id); |
| 124 | match usbfs::reap_urb_ndelay(&self.fd) { |
| 125 | Ok(urb_ptr) => { |
| 126 | let user_data = { |
| 127 | let urb = unsafe { &*urb_ptr }; |
| 128 | debug!( |
| 129 | "URB {:?} for ep {:x} completed, status={} actual_length={}", |
| 130 | urb_ptr, urb.endpoint, urb.status, urb.actual_length |
| 131 | ); |
| 132 | urb.usercontext |
| 133 | }; |
| 134 | |
| 135 | // SAFETY: pointer came from submit via kernel an we're now done with it |
| 136 | unsafe { notify_completion::<super::TransferData>(user_data) } |
| 137 | } |
| 138 | Err(Errno::AGAIN) => {} |
| 139 | Err(Errno::NODEV) => { |
| 140 | debug!("Device {} disconnected", self.events_id); |
| 141 | |
| 142 | // epoll returns events continuously on a disconnected device, and REAPURB |
| 143 | // only returns ENODEV after all events are received, so unregister to |
| 144 | // keep the event thread from spinning because we won't receive further events. |
| 145 | // The drop impl will try to unregister again, but that's ok. |
| 146 | events::unregister_fd(self.fd.as_fd()); |
| 147 | } |
| 148 | Err(e) => { |
| 149 | error!("Unexpected error {e} from REAPURBNDELAY"); |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | pub(crate) fn configuration_descriptors(&self) -> impl Iterator<Item = &[u8]> { |
| 155 | parse_concatenated_config_descriptors(&self.descriptors[DESCRIPTOR_LEN_DEVICE as usize..]) |
| 156 | } |
| 157 | |
| 158 | pub(crate) fn active_configuration_value(&self) -> u8 { |
| 159 | if let Some(sysfs) = self.sysfs.as_ref() { |
| 160 | match sysfs.read_attr("bConfigurationValue") { |
| 161 | Ok(v) => { |
| 162 | self.active_config.store(v, Ordering::SeqCst); |
| 163 | return v; |
| 164 | } |
| 165 | Err(e) => { |
| 166 | error!("Failed to read sysfs bConfigurationValue: {e}, using cached value"); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | self.active_config.load(Ordering::SeqCst) |
| 171 | } |
| 172 | |
| 173 | pub(crate) fn set_configuration(&self, configuration: u8) -> Result<(), Error> { |
| 174 | usbfs::set_configuration(&self.fd, configuration)?; |
| 175 | self.active_config.store(configuration, Ordering::SeqCst); |
| 176 | Ok(()) |
| 177 | } |
| 178 | |
| 179 | pub(crate) fn reset(&self) -> Result<(), Error> { |
| 180 | usbfs::reset(&self.fd)?; |
| 181 | Ok(()) |
| 182 | } |
| 183 | |
| 184 | /// SAFETY: `data` must be valid for `len` bytes to read or write, depending on `Direction` |
| 185 | unsafe fn control_blocking( |
| 186 | &self, |
| 187 | direction: Direction, |
| 188 | control: Control, |
| 189 | data: *mut u8, |
| 190 | len: usize, |
| 191 | timeout: Duration, |
| 192 | ) -> Result<usize, TransferError> { |
| 193 | let r = usbfs::control( |
| 194 | &self.fd, |
| 195 | usbfs::CtrlTransfer { |
| 196 | bRequestType: control.request_type(direction), |
| 197 | bRequest: control.request, |
| 198 | wValue: control.value, |
| 199 | wIndex: control.index, |
| 200 | wLength: len.try_into().expect("length must fit in u16"), |
| 201 | timeout: timeout |
| 202 | .as_millis() |
| 203 | .try_into() |
| 204 | .expect("timeout must fit in u32 ms"), |
| 205 | data: data as *mut c_void, |
| 206 | }, |
| 207 | ); |
| 208 | |
| 209 | r.map_err(errno_to_transfer_error) |
| 210 | } |
| 211 | |
| 212 | pub fn control_in_blocking( |
| 213 | &self, |
| 214 | control: Control, |
| 215 | data: &mut [u8], |
| 216 | timeout: Duration, |
| 217 | ) -> Result<usize, TransferError> { |
| 218 | unsafe { |
| 219 | self.control_blocking( |
| 220 | Direction::In, |
| 221 | control, |
| 222 | data.as_mut_ptr(), |
| 223 | data.len(), |
| 224 | timeout, |
| 225 | ) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | pub fn control_out_blocking( |
| 230 | &self, |
| 231 | control: Control, |
| 232 | data: &[u8], |
| 233 | timeout: Duration, |
| 234 | ) -> Result<usize, TransferError> { |
| 235 | unsafe { |
| 236 | self.control_blocking( |
| 237 | Direction::Out, |
| 238 | control, |
| 239 | data.as_ptr() as *mut u8, |
| 240 | data.len(), |
| 241 | timeout, |
| 242 | ) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | pub(crate) fn make_control_transfer(self: &Arc<Self>) -> TransferHandle<super::TransferData> { |
| 247 | TransferHandle::new(super::TransferData::new( |
| 248 | self.clone(), |
| 249 | None, |
| 250 | 0, |
| 251 | EndpointType::Control, |
| 252 | )) |
| 253 | } |
| 254 | |
| 255 | pub(crate) fn claim_interface( |
| 256 | self: &Arc<Self>, |
| 257 | interface_number: u8, |
| 258 | ) -> Result<Arc<LinuxInterface>, Error> { |
| 259 | usbfs::claim_interface(&self.fd, interface_number)?; |
| 260 | debug!( |
| 261 | "Claimed interface {interface_number} on device id {dev}", |
| 262 | dev = self.events_id |
| 263 | ); |
| 264 | Ok(Arc::new(LinuxInterface { |
| 265 | device: self.clone(), |
| 266 | interface_number, |
| 267 | reattach: false, |
| 268 | })) |
| 269 | } |
| 270 | |
| 271 | pub(crate) fn detach_and_claim_interface( |
| 272 | self: &Arc<Self>, |
| 273 | interface_number: u8, |
| 274 | ) -> Result<Arc<LinuxInterface>, Error> { |
| 275 | usbfs::detach_and_claim_interface(&self.fd, interface_number)?; |
| 276 | debug!( |
| 277 | "Detached and claimed interface {interface_number} on device id {dev}", |
| 278 | dev = self.events_id |
| 279 | ); |
| 280 | Ok(Arc::new(LinuxInterface { |
| 281 | device: self.clone(), |
| 282 | interface_number, |
| 283 | reattach: true, |
| 284 | })) |
| 285 | } |
| 286 | |
| 287 | pub(crate) fn detach_kernel_driver( |
| 288 | self: &Arc<Self>, |
| 289 | interface_number: u8, |
| 290 | ) -> Result<(), Error> { |
| 291 | usbfs::detach_kernel_driver(&self.fd, interface_number).map_err(|e| e.into()) |
| 292 | } |
| 293 | |
| 294 | pub(crate) fn attach_kernel_driver( |
| 295 | self: &Arc<Self>, |
| 296 | interface_number: u8, |
| 297 | ) -> Result<(), Error> { |
| 298 | usbfs::attach_kernel_driver(&self.fd, interface_number).map_err(|e| e.into()) |
| 299 | } |
| 300 | |
| 301 | pub(crate) unsafe fn submit_urb(&self, urb: *mut Urb) { |
| 302 | let ep = unsafe { (*urb).endpoint }; |
| 303 | if let Err(e) = usbfs::submit_urb(&self.fd, urb) { |
| 304 | // SAFETY: Transfer was not submitted. We still own the transfer |
| 305 | // and can write to the URB and complete it in place of the handler. |
| 306 | unsafe { |
| 307 | let user_data = { |
| 308 | let u = &mut *urb; |
| 309 | debug!("Failed to submit URB {urb:?} on ep {ep:x}: {e} {u:?}"); |
| 310 | u.actual_length = 0; |
| 311 | u.status = e.raw_os_error(); |
| 312 | u.usercontext |
| 313 | }; |
| 314 | notify_completion::<super::TransferData>(user_data) |
| 315 | } |
| 316 | } else { |
| 317 | debug!("Submitted URB {urb:?} on ep {ep:x}"); |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | pub(crate) unsafe fn cancel_urb(&self, urb: *mut Urb) { |
| 322 | unsafe { |
| 323 | if let Err(e) = usbfs::discard_urb(&self.fd, urb) { |
| 324 | debug!("Failed to cancel URB {urb:?}: {e}"); |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | fn get_config(descriptors: &[u8], fd: &OwnedFd) -> Result<u8, Error> { |
| 330 | const REQUEST_GET_CONFIGURATION: u8 = 0x08; |
| 331 | |
| 332 | let mut dst = [0u8; 1]; |
| 333 | |
| 334 | let control = Control { |
| 335 | control_type: ControlType::Standard, |
| 336 | recipient: Recipient::Device, |
| 337 | request: REQUEST_GET_CONFIGURATION, |
| 338 | value: 0, |
| 339 | index: 0, |
| 340 | }; |
| 341 | |
| 342 | let r = usbfs::control( |
| 343 | &fd, |
| 344 | usbfs::CtrlTransfer { |
| 345 | bRequestType: control.request_type(Direction::In), |
| 346 | bRequest: control.request, |
| 347 | wValue: control.value, |
| 348 | wIndex: control.index, |
| 349 | wLength: dst.len() as u16, |
| 350 | timeout: Duration::from_millis(50) |
| 351 | .as_millis() |
| 352 | .try_into() |
| 353 | .expect("timeout must fit in u32 ms"), |
| 354 | data: &mut dst[0] as *mut u8 as *mut c_void, |
| 355 | }, |
| 356 | ); |
| 357 | |
| 358 | match r { |
| 359 | Ok(n) => { |
| 360 | if n == dst.len() { |
| 361 | let active_config = dst[0]; |
| 362 | debug!("Obtained active configuration for fd {} from GET_CONFIGURATION request: {active_config}", fd.as_raw_fd()); |
| 363 | return Ok(active_config); |
| 364 | } else { |
| 365 | warn!("GET_CONFIGURATION request returned incorrect length: {n}, expected 1",); |
| 366 | } |
| 367 | } |
| 368 | Err(e) => { |
| 369 | warn!( |
| 370 | "GET_CONFIGURATION request failed: {:?}", |
| 371 | errno_to_transfer_error(e) |
| 372 | ); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | if descriptors.len() < DESCRIPTOR_LEN_DEVICE as usize { |
| 377 | warn!( |
| 378 | "Descriptors for device fd {} too short to use fallback configuration", |
| 379 | fd.as_raw_fd() |
| 380 | ); |
| 381 | return Err(ErrorKind::Other.into()); |
| 382 | } |
| 383 | |
| 384 | // Assume the current configuration is the first one |
| 385 | // See: https://github.com/libusb/libusb/blob/467b6a8896daea3d104958bf0887312c5d14d150/libusb/os/linux_usbfs.c#L865 |
| 386 | let mut descriptors = |
| 387 | parse_concatenated_config_descriptors(&descriptors[DESCRIPTOR_LEN_DEVICE as usize..]) |
| 388 | .map(Configuration::new); |
| 389 | |
| 390 | if let Some(config) = descriptors.next() { |
| 391 | return Ok(config.configuration_value()); |
| 392 | } |
| 393 | |
| 394 | error!( |
| 395 | "No available configurations for device fd {}", |
| 396 | fd.as_raw_fd() |
| 397 | ); |
| 398 | return Err(ErrorKind::Other.into()); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | impl Drop for LinuxDevice { |
| 403 | fn drop(&mut self) { |
| 404 | debug!("Closing device {}", self.events_id); |
| 405 | events::unregister(self.fd.as_fd(), self.events_id) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | pub(crate) struct LinuxInterface { |
| 410 | pub(crate) interface_number: u8, |
| 411 | pub(crate) device: Arc<LinuxDevice>, |
| 412 | pub(crate) reattach: bool, |
| 413 | } |
| 414 | |
| 415 | impl LinuxInterface { |
| 416 | pub(crate) fn make_transfer( |
| 417 | self: &Arc<Self>, |
| 418 | endpoint: u8, |
| 419 | ep_type: EndpointType, |
| 420 | ) -> TransferHandle<super::TransferData> { |
| 421 | TransferHandle::new(super::TransferData::new( |
| 422 | self.device.clone(), |
| 423 | Some(self.clone()), |
| 424 | endpoint, |
| 425 | ep_type, |
| 426 | )) |
| 427 | } |
| 428 | |
| 429 | pub fn control_in_blocking( |
| 430 | &self, |
| 431 | control: Control, |
| 432 | data: &mut [u8], |
| 433 | timeout: Duration, |
| 434 | ) -> Result<usize, TransferError> { |
| 435 | self.device.control_in_blocking(control, data, timeout) |
| 436 | } |
| 437 | |
| 438 | pub fn control_out_blocking( |
| 439 | &self, |
| 440 | control: Control, |
| 441 | data: &[u8], |
| 442 | timeout: Duration, |
| 443 | ) -> Result<usize, TransferError> { |
| 444 | self.device.control_out_blocking(control, data, timeout) |
| 445 | } |
| 446 | |
| 447 | pub fn set_alt_setting(&self, alt_setting: u8) -> Result<(), Error> { |
| 448 | debug!( |
| 449 | "Set interface {} alt setting to {alt_setting}", |
| 450 | self.interface_number |
| 451 | ); |
| 452 | Ok(usbfs::set_interface( |
| 453 | &self.device.fd, |
| 454 | self.interface_number, |
| 455 | alt_setting, |
| 456 | )?) |
| 457 | } |
| 458 | |
| 459 | pub fn clear_halt(&self, endpoint: u8) -> Result<(), Error> { |
| 460 | debug!("Clear halt, endpoint {endpoint:02x}"); |
| 461 | Ok(usbfs::clear_halt(&self.device.fd, endpoint)?) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | impl Drop for LinuxInterface { |
| 466 | fn drop(&mut self) { |
| 467 | let res = usbfs::release_interface(&self.device.fd, self.interface_number); |
| 468 | debug!( |
| 469 | "Released interface {} on device {}: {res:?}", |
| 470 | self.interface_number, self.device.events_id |
| 471 | ); |
| 472 | |
| 473 | if res.is_ok() && self.reattach { |
| 474 | let res = usbfs::attach_kernel_driver(&self.device.fd, self.interface_number); |
| 475 | debug!( |
| 476 | "Reattached kernel drivers for interface {} on device {}: {res:?}", |
| 477 | self.interface_number, self.device.events_id |
| 478 | ); |
| 479 | } |
| 480 | } |
| 481 | } |