| 1 | //! Utilities for parsing USB descriptors. |
| 2 | //! |
| 3 | //! Descriptors are blocks of data that describe the functionality of a USB device. |
| 4 | |
| 5 | use std::{ |
| 6 | collections::BTreeMap, |
| 7 | fmt::{Debug, Display}, |
| 8 | io::ErrorKind, |
| 9 | iter, |
| 10 | ops::Deref, |
| 11 | }; |
| 12 | |
| 13 | use log::warn; |
| 14 | |
| 15 | use crate::{ |
| 16 | transfer::{Direction, EndpointType}, |
| 17 | Error, |
| 18 | }; |
| 19 | |
| 20 | #[allow(dead_code)] |
| 21 | pub(crate) const DESCRIPTOR_TYPE_DEVICE: u8 = 0x01; |
| 22 | pub(crate) const DESCRIPTOR_LEN_DEVICE: u8 = 18; |
| 23 | |
| 24 | pub(crate) const DESCRIPTOR_TYPE_CONFIGURATION: u8 = 0x02; |
| 25 | pub(crate) const DESCRIPTOR_LEN_CONFIGURATION: u8 = 9; |
| 26 | |
| 27 | pub(crate) const DESCRIPTOR_TYPE_INTERFACE: u8 = 0x04; |
| 28 | pub(crate) const DESCRIPTOR_LEN_INTERFACE: u8 = 9; |
| 29 | |
| 30 | pub(crate) const DESCRIPTOR_TYPE_ENDPOINT: u8 = 0x05; |
| 31 | pub(crate) const DESCRIPTOR_LEN_ENDPOINT: u8 = 7; |
| 32 | |
| 33 | pub(crate) const DESCRIPTOR_TYPE_STRING: u8 = 0x03; |
| 34 | |
| 35 | /// USB defined language IDs for string descriptors. |
| 36 | /// |
| 37 | /// In practice, different language IDs are not used, |
| 38 | /// and device string descriptors are only provided |
| 39 | /// with [`language_id::US_ENGLISH`]. |
| 40 | pub mod language_id { |
| 41 | /// US English |
| 42 | pub const US_ENGLISH: u16 = 0x0409; |
| 43 | } |
| 44 | |
| 45 | /// A raw USB descriptor. |
| 46 | /// |
| 47 | /// Wraps a byte slice to provide access to the bytes of a descriptor by implementing `Deref` to `[u8]`, |
| 48 | /// while also exposing the descriptor length and type. |
| 49 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 50 | pub struct Descriptor<'a>(&'a [u8]); |
| 51 | |
| 52 | impl<'a> Descriptor<'a> { |
| 53 | /// Create a `Descriptor` from a buffer. |
| 54 | /// |
| 55 | /// Returns `None` if |
| 56 | /// * the slice length is not at least 2. |
| 57 | /// * the `bLength` field (first byte) is greater than the slice length. |
| 58 | pub fn new(buf: &[u8]) -> Option<Descriptor> { |
| 59 | if buf.len() >= 2 && buf.len() >= buf[0] as usize { |
| 60 | Some(Descriptor(buf)) |
| 61 | } else { |
| 62 | None |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /// Get the length field of the descriptor. |
| 67 | #[doc(alias = "bLength")] |
| 68 | pub fn descriptor_len(&self) -> usize { |
| 69 | self.0[0] as usize |
| 70 | } |
| 71 | |
| 72 | /// Get the type field of the descriptor. |
| 73 | #[doc(alias = "bDescriptorType")] |
| 74 | pub fn descriptor_type(&self) -> u8 { |
| 75 | self.0[1] |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl<'a> Deref for Descriptor<'a> { |
| 80 | type Target = [u8]; |
| 81 | |
| 82 | fn deref(&self) -> &[u8] { |
| 83 | self.0 |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// An iterator over a sequence of USB descriptors. |
| 88 | #[derive(Clone)] |
| 89 | pub struct Descriptors<'a>(&'a [u8]); |
| 90 | |
| 91 | impl<'a> Descriptors<'a> { |
| 92 | /// Get the concatenated bytes of the remaining descriptors. |
| 93 | pub fn as_bytes(&self) -> &'a [u8] { |
| 94 | self.0 |
| 95 | } |
| 96 | |
| 97 | fn split_first(&self) -> Option<(&'a [u8], &'a [u8])> { |
| 98 | if self.0.len() < 2 { |
| 99 | return None; |
| 100 | } |
| 101 | |
| 102 | if self.0[0] < 2 { |
| 103 | warn!( |
| 104 | "descriptor with bLength {} can't point to next descriptor", |
| 105 | self.0[0] |
| 106 | ); |
| 107 | return None; |
| 108 | } |
| 109 | |
| 110 | if self.0[0] as usize > self.0.len() { |
| 111 | warn!( |
| 112 | "descriptor with bLength {} exceeds remaining buffer length {}", |
| 113 | self.0[0], |
| 114 | self.0.len() |
| 115 | ); |
| 116 | return None; |
| 117 | } |
| 118 | |
| 119 | Some(self.0.split_at(self.0[0] as usize)) |
| 120 | } |
| 121 | |
| 122 | fn split_by_type(mut self, descriptor_type: u8, min_len: u8) -> impl Iterator<Item = &'a [u8]> { |
| 123 | iter::from_fn(move || { |
| 124 | loop { |
| 125 | let (_, next) = self.split_first()?; |
| 126 | |
| 127 | if self.0[1] == descriptor_type { |
| 128 | if self.0[0] >= min_len { |
| 129 | break; |
| 130 | } else { |
| 131 | warn!("ignoring descriptor of type {} and length {} because the minimum length is {}", self.0[1], self.0[0], min_len); |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | self.0 = next; |
| 136 | } |
| 137 | |
| 138 | let mut end = self.0[0] as usize; |
| 139 | |
| 140 | while self.0.len() >= end + 2 |
| 141 | && self.0[end] > 2 |
| 142 | && self.0[end + 1] != descriptor_type |
| 143 | && self.0.len() >= end + self.0[end] as usize |
| 144 | { |
| 145 | end += self.0[end] as usize; |
| 146 | } |
| 147 | |
| 148 | let (r, next) = self.0.split_at(end); |
| 149 | self.0 = next; |
| 150 | Some(r) |
| 151 | }) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | impl<'a> Iterator for Descriptors<'a> { |
| 156 | type Item = Descriptor<'a>; |
| 157 | |
| 158 | fn next(&mut self) -> Option<Self::Item> { |
| 159 | if let Some((cur, next)) = self.split_first() { |
| 160 | self.0 = next; |
| 161 | Some(Descriptor(cur)) |
| 162 | } else { |
| 163 | None |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | macro_rules! descriptor_fields { |
| 169 | (impl<'a> $tname:ident<'a> { |
| 170 | $( |
| 171 | $(#[$attr:meta])* |
| 172 | $vis:vis fn $name:ident at $pos:literal -> $ty:ty; |
| 173 | )* |
| 174 | }) => { |
| 175 | impl<'a> $tname<'a> { |
| 176 | $( |
| 177 | $(#[$attr])* |
| 178 | #[inline] |
| 179 | $vis fn $name(&self) -> $ty { <$ty>::from_le_bytes(self.0[$pos..$pos + std::mem::size_of::<$ty>()].try_into().unwrap()) } |
| 180 | )* |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | pub(crate) fn validate_config_descriptor(buf: &[u8]) -> Option<usize> { |
| 186 | if buf.len() < DESCRIPTOR_LEN_CONFIGURATION as usize { |
| 187 | if buf.len() != 0 { |
| 188 | warn!( |
| 189 | "config descriptor buffer is {} bytes, need {}", |
| 190 | buf.len(), |
| 191 | DESCRIPTOR_LEN_CONFIGURATION |
| 192 | ); |
| 193 | } |
| 194 | return None; |
| 195 | } |
| 196 | |
| 197 | if buf[0] < DESCRIPTOR_LEN_CONFIGURATION { |
| 198 | warn!("invalid config descriptor bLength"); |
| 199 | return None; |
| 200 | } |
| 201 | |
| 202 | if buf[1] != DESCRIPTOR_TYPE_CONFIGURATION { |
| 203 | warn!( |
| 204 | "config bDescriptorType is {}, not a configuration descriptor", |
| 205 | buf[0] |
| 206 | ); |
| 207 | return None; |
| 208 | } |
| 209 | |
| 210 | let total_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()) as usize; |
| 211 | if total_len < buf[0] as usize || total_len > buf.len() { |
| 212 | warn!( |
| 213 | "invalid config descriptor wTotalLen of {total_len} (buffer size is {bufsize})", |
| 214 | bufsize = buf.len() |
| 215 | ); |
| 216 | return None; |
| 217 | } |
| 218 | |
| 219 | Some(total_len) |
| 220 | } |
| 221 | |
| 222 | /// Information about a USB configuration with access to all associated interfaces, endpoints, and other descriptors. |
| 223 | #[derive(Clone)] |
| 224 | pub struct Configuration<'a>(&'a [u8]); |
| 225 | |
| 226 | impl<'a> Configuration<'a> { |
| 227 | /// Create a `Configuration` from a buffer containing a series of descriptors. |
| 228 | /// |
| 229 | /// You normally obtain a `Configuration` from a [`Device`][crate::Device], but this allows creating |
| 230 | /// one from your own descriptor bytes for tests. |
| 231 | /// |
| 232 | /// ### Panics |
| 233 | /// * when the buffer is too short for a configuration descriptor |
| 234 | /// * when the bLength and wTotalLength fields are longer than the buffer |
| 235 | /// * when the first descriptor is not a configuration descriptor |
| 236 | pub fn new(buf: &[u8]) -> Configuration { |
| 237 | assert!(buf.len() >= DESCRIPTOR_LEN_CONFIGURATION as usize); |
| 238 | assert!(buf[0] as usize >= DESCRIPTOR_LEN_CONFIGURATION as usize); |
| 239 | assert!(buf[1] == DESCRIPTOR_TYPE_CONFIGURATION); |
| 240 | assert!(buf.len() == u16::from_le_bytes(buf[2..4].try_into().unwrap()) as usize); |
| 241 | Configuration(buf) |
| 242 | } |
| 243 | |
| 244 | /// Get the configuration descriptor followed by all trailing interface and other descriptors. |
| 245 | pub fn descriptors(&self) -> Descriptors<'a> { |
| 246 | Descriptors(self.0) |
| 247 | } |
| 248 | |
| 249 | /// Iterate all interfaces and alternate settings settings of this configuration. |
| 250 | pub fn interface_alt_settings(&self) -> impl Iterator<Item = InterfaceAltSetting<'a>> { |
| 251 | self.descriptors() |
| 252 | .split_by_type(DESCRIPTOR_TYPE_INTERFACE, DESCRIPTOR_LEN_INTERFACE) |
| 253 | .map(InterfaceAltSetting) |
| 254 | } |
| 255 | |
| 256 | /// Iterate the interfaces of this configuration, grouping together alternate settings of the same interface. |
| 257 | pub fn interfaces(&self) -> impl Iterator<Item = InterfaceGroup<'a>> { |
| 258 | let mut interfaces = BTreeMap::new(); |
| 259 | |
| 260 | for intf in self.interface_alt_settings() { |
| 261 | interfaces |
| 262 | .entry(intf.interface_number()) |
| 263 | .or_insert_with(Vec::new) |
| 264 | .push(intf); |
| 265 | } |
| 266 | |
| 267 | interfaces |
| 268 | .into_iter() |
| 269 | .map(|(intf_number, interfaces)| InterfaceGroup { |
| 270 | intf_number, |
| 271 | interfaces, |
| 272 | }) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | descriptor_fields! { |
| 277 | impl<'a> Configuration<'a> { |
| 278 | /// `bNumInterfaces` descriptor field: Number of interfaces. |
| 279 | #[doc(alias = "bNumInterfaces")] |
| 280 | pub fn num_interfaces at 4 -> u8; |
| 281 | |
| 282 | /// `bConfigurationValue` descriptor field: Identifier for the configuration. |
| 283 | /// |
| 284 | /// Pass this value to |
| 285 | /// [`Device::set_configuration`][crate::Device::set_configuration] to |
| 286 | /// select this configuration. |
| 287 | #[doc(alias = "bConfigurationValue")] |
| 288 | pub fn configuration_value at 5 -> u8; |
| 289 | |
| 290 | fn string_index_raw at 6 -> u8; |
| 291 | |
| 292 | /// `bmAttributes` descriptor field: Bitmap of configuration attributes. |
| 293 | #[doc(alias = "bmAttributes")] |
| 294 | pub fn attributes at 7 -> u8; |
| 295 | |
| 296 | /// `bMaxPower` descriptor field: Maximum power, in units of **2** milliamps. |
| 297 | #[doc(alias = "bMaxPower")] |
| 298 | pub fn max_power at 8 -> u8; |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | impl<'a> Configuration<'a> { |
| 303 | /// Index of the string descriptor describing this configuration. |
| 304 | #[doc(alias = "iConfiguration")] |
| 305 | pub fn string_index(&self) -> Option<u8> { |
| 306 | Some(self.string_index_raw()).filter(|&i| i != 0) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | struct DebugEntries<F>(F); |
| 311 | |
| 312 | impl<F, I> Debug for DebugEntries<F> |
| 313 | where |
| 314 | F: Fn() -> I, |
| 315 | I: Iterator, |
| 316 | I::Item: Debug, |
| 317 | { |
| 318 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 319 | f.debug_list().entries(self.0()).finish() |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | impl<'a> Debug for Configuration<'a> { |
| 324 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 325 | f.debug_struct("Configuration") |
| 326 | .field("configuration_value", &self.configuration_value()) |
| 327 | .field("num_interfaces", &self.num_interfaces()) |
| 328 | .field("attributes", &self.attributes()) |
| 329 | .field("max_power", &self.max_power()) |
| 330 | .field("string_index", &self.string_index()) |
| 331 | .field( |
| 332 | "interface_alt_settings", |
| 333 | &DebugEntries(|| self.interface_alt_settings()), |
| 334 | ) |
| 335 | .finish() |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /// Interface descriptors for alternate settings, grouped by the interface number. |
| 340 | #[derive(Clone)] |
| 341 | pub struct InterfaceGroup<'a> { |
| 342 | intf_number: u8, |
| 343 | interfaces: Vec<InterfaceAltSetting<'a>>, |
| 344 | } |
| 345 | |
| 346 | impl<'a> InterfaceGroup<'a> { |
| 347 | /// `bInterfaceNumber` descriptor field: Identifier for the interface. |
| 348 | /// |
| 349 | /// Pass this to [`Device::claim_interface`][crate::Device::claim_interface] to work with the interface. |
| 350 | #[doc(alias = "bInterfaceNumber")] |
| 351 | pub fn interface_number(&self) -> u8 { |
| 352 | self.intf_number |
| 353 | } |
| 354 | |
| 355 | /// Iterator over alternate settings of the interface. |
| 356 | pub fn alt_settings(&self) -> impl Iterator<Item = InterfaceAltSetting> { |
| 357 | self.interfaces.iter().cloned() |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// Information about a USB interface alternate setting, with access to associated endpoints and other descriptors. |
| 362 | /// |
| 363 | /// An interface descriptor represents a single alternate setting of |
| 364 | /// an interface. Multiple interface descriptors with the same [`interface_number`][Self::interface_number] |
| 365 | /// but different [`alternate_setting`][Self::alternate_setting] values represent different alternate settings. |
| 366 | #[derive(Clone)] |
| 367 | pub struct InterfaceAltSetting<'a>(&'a [u8]); |
| 368 | |
| 369 | impl<'a> InterfaceAltSetting<'a> { |
| 370 | /// Get the interface descriptor followed by all trailing endpoint and other |
| 371 | /// descriptors up to the next interface descriptor. |
| 372 | pub fn descriptors(&self) -> Descriptors { |
| 373 | Descriptors(self.0) |
| 374 | } |
| 375 | |
| 376 | /// Get the endpoints of this interface. |
| 377 | pub fn endpoints(&self) -> impl Iterator<Item = Endpoint> { |
| 378 | self.descriptors() |
| 379 | .split_by_type(DESCRIPTOR_TYPE_ENDPOINT, DESCRIPTOR_LEN_ENDPOINT) |
| 380 | .map(Endpoint) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | descriptor_fields! { |
| 385 | impl<'a> InterfaceAltSetting<'a> { |
| 386 | /// `bInterfaceNumber` descriptor field: Identifier for the interface. |
| 387 | /// |
| 388 | /// Pass this to [`Device::claim_interface`][crate::Device::claim_interface] to work with the interface. |
| 389 | #[doc(alias="bInterfaceNumber")] |
| 390 | pub fn interface_number at 2 -> u8; |
| 391 | |
| 392 | /// `bAlternateSetting` descriptor field: Identifier for this alternate setting. |
| 393 | /// |
| 394 | /// Pass this to [`Interface::set_alt_setting`][crate::Interface::set_alt_setting] to use this alternate setting. |
| 395 | #[doc(alias="bAlternateSetting")] |
| 396 | pub fn alternate_setting at 3 -> u8; |
| 397 | |
| 398 | /// `bNumEndpoints` descriptor field: Number of endpoints in this alternate setting. |
| 399 | #[doc(alias="bNumEndpoints")] |
| 400 | pub fn num_endpoints at 4 -> u8; |
| 401 | |
| 402 | /// `bInterfaceClass` descriptor field: Standard interface class. |
| 403 | #[doc(alias="bInterfaceClass")] |
| 404 | pub fn class at 5 -> u8; |
| 405 | |
| 406 | /// `bInterfaceSubClass` descriptor field: Standard interface subclass. |
| 407 | #[doc(alias="bInterfaceSubClass")] |
| 408 | pub fn subclass at 6 -> u8; |
| 409 | |
| 410 | /// `bInterfaceProtocol` descriptor field: Standard interface protocol. |
| 411 | #[doc(alias="bInterfaceProtocol")] |
| 412 | pub fn protocol at 7 -> u8; |
| 413 | |
| 414 | fn string_index_raw at 8 -> u8; |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | impl<'a> InterfaceAltSetting<'a> { |
| 419 | /// Index of the string descriptor describing this interface or alternate setting. |
| 420 | #[doc(alias = "iInterface")] |
| 421 | pub fn string_index(&self) -> Option<u8> { |
| 422 | Some(self.string_index_raw()).filter(|&i| i != 0) |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | impl<'a> Debug for InterfaceAltSetting<'a> { |
| 427 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 428 | f.debug_struct("InterfaceAltSetting") |
| 429 | .field("interface_number", &self.interface_number()) |
| 430 | .field("alternate_setting", &self.alternate_setting()) |
| 431 | .field("num_endpoints", &self.num_endpoints()) |
| 432 | .field("class", &self.class()) |
| 433 | .field("subclass", &self.subclass()) |
| 434 | .field("protocol", &self.protocol()) |
| 435 | .field("string_index", &self.string_index()) |
| 436 | .field("endpoints", &DebugEntries(|| self.endpoints())) |
| 437 | .finish() |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | /// Information about a USB endpoint, with access to any associated descriptors. |
| 442 | pub struct Endpoint<'a>(&'a [u8]); |
| 443 | |
| 444 | impl<'a> Endpoint<'a> { |
| 445 | /// Get the endpoint descriptor followed by all trailing descriptors up to the next endpoint or interface descriptor. |
| 446 | pub fn descriptors(&self) -> impl Iterator<Item = Descriptor> { |
| 447 | Descriptors(self.0) |
| 448 | } |
| 449 | |
| 450 | /// Get the endpoint's direction. |
| 451 | pub fn direction(&self) -> Direction { |
| 452 | match self.address() & 0x80 { |
| 453 | 0 => Direction::Out, |
| 454 | _ => Direction::In, |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | /// Get the endpoint's transfer type. |
| 459 | pub fn transfer_type(&self) -> EndpointType { |
| 460 | match self.attributes() & 0x03 { |
| 461 | 0 => EndpointType::Control, |
| 462 | 1 => EndpointType::Isochronous, |
| 463 | 2 => EndpointType::Bulk, |
| 464 | 3 => EndpointType::Interrupt, |
| 465 | _ => unreachable!(), |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /// Get the maximum packet size in bytes. |
| 470 | pub fn max_packet_size(&self) -> usize { |
| 471 | (self.max_packet_size_raw() & ((1 << 11) - 1)) as usize |
| 472 | } |
| 473 | |
| 474 | /// For isochronous endpoints at high speed, get the number of packets per microframe (1, 2, or 3). |
| 475 | pub fn packets_per_microframe(&self) -> u8 { |
| 476 | ((self.max_packet_size_raw() >> 11) & 0b11) as u8 + 1 |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | descriptor_fields! { |
| 481 | impl<'a> Endpoint<'a> { |
| 482 | /// Get the `bEndpointAddress` descriptor field: Endpoint address. |
| 483 | #[doc(alias = "bEndpointAddress")] |
| 484 | pub fn address at 2 -> u8; |
| 485 | |
| 486 | /// Get the raw value of the `bmAttributes` descriptor field. |
| 487 | /// |
| 488 | /// See [`transfer_type``][Self::transfer_type] for the transfer type field. |
| 489 | #[doc(alias = "bmAttributes")] |
| 490 | pub fn attributes at 3 -> u8; |
| 491 | |
| 492 | /// Get the raw value of the `wMaxPacketSize` descriptor field. |
| 493 | /// |
| 494 | /// See [`max_macket_size`][Self::max_packet_size] and [`packets_per_microframe`][Self::packets_per_microframe] |
| 495 | /// for the parsed subfields. |
| 496 | #[doc(alias = "wMaxPacketSize")] |
| 497 | pub fn max_packet_size_raw at 4 -> u16; |
| 498 | |
| 499 | /// Get the `bInterval` field: Polling interval in frames or microframes. |
| 500 | #[doc(alias = "bInterval")] |
| 501 | pub fn interval at 6 -> u8; |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | impl<'a> Debug for Endpoint<'a> { |
| 506 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 507 | f.debug_struct("Endpoint") |
| 508 | .field("address", &format_args!("0x{:02X}", self.address())) |
| 509 | .field("direction", &self.direction()) |
| 510 | .field("transfer_type", &self.transfer_type()) |
| 511 | .field("max_packet_size", &self.max_packet_size()) |
| 512 | .field("packets_per_microframe", &self.packets_per_microframe()) |
| 513 | .field("interval", &self.interval()) |
| 514 | .finish() |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | /// Error from [`crate::Device::active_configuration`] |
| 519 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] |
| 520 | pub struct ActiveConfigurationError { |
| 521 | pub(crate) configuration_value: u8, |
| 522 | } |
| 523 | |
| 524 | impl Display for ActiveConfigurationError { |
| 525 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 526 | if self.configuration_value == 0 { |
| 527 | write!(f, "device is not configured") |
| 528 | } else { |
| 529 | write!( |
| 530 | f, |
| 531 | "no descriptor found for active configuration {}", |
| 532 | self.configuration_value |
| 533 | ) |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | impl std::error::Error for ActiveConfigurationError {} |
| 539 | |
| 540 | impl From<ActiveConfigurationError> for Error { |
| 541 | fn from(value: ActiveConfigurationError) -> Self { |
| 542 | Error::new(ErrorKind::Other, value) |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | /// Split a chain of concatenated configuration descriptors by `wTotalLength` |
| 547 | pub(crate) fn parse_concatenated_config_descriptors(mut buf: &[u8]) -> impl Iterator<Item = &[u8]> { |
| 548 | iter::from_fn(move || { |
| 549 | let total_len = validate_config_descriptor(buf)?; |
| 550 | let descriptors = &buf[..total_len]; |
| 551 | buf = &buf[total_len..]; |
| 552 | Some(descriptors) |
| 553 | }) |
| 554 | } |
| 555 | |
| 556 | pub(crate) fn validate_string_descriptor(data: &[u8]) -> bool { |
| 557 | data.len() >= 2 && data[0] as usize == data.len() && data[1] == DESCRIPTOR_TYPE_STRING |
| 558 | } |
| 559 | |
| 560 | pub(crate) fn decode_string_descriptor(data: &[u8]) -> Result<String, ()> { |
| 561 | if !validate_string_descriptor(data) { |
| 562 | return Err(()); |
| 563 | } |
| 564 | |
| 565 | Ok(char::decode_utf16( |
| 566 | data[2..] |
| 567 | .chunks_exact(2) |
| 568 | .map(|c| u16::from_le_bytes(c.try_into().unwrap())), |
| 569 | ) |
| 570 | .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)) |
| 571 | .collect::<String>()) |
| 572 | } |
| 573 | |
| 574 | /// Make public when fuzzing |
| 575 | #[cfg(fuzzing)] |
| 576 | pub fn fuzz_parse_concatenated_config_descriptors(buf: &[u8]) -> impl Iterator<Item = &[u8]> { |
| 577 | parse_concatenated_config_descriptors(buf) |
| 578 | } |
| 579 | |
| 580 | #[cfg(test)] |
| 581 | mod test_concatenated { |
| 582 | use super::parse_concatenated_config_descriptors; |
| 583 | |
| 584 | #[test] |
| 585 | fn test_empty() { |
| 586 | assert_eq!( |
| 587 | parse_concatenated_config_descriptors(&[]).collect::<Vec<&[u8]>>(), |
| 588 | Vec::<&[u8]>::new() |
| 589 | ); |
| 590 | } |
| 591 | |
| 592 | #[test] |
| 593 | fn test_short() { |
| 594 | assert_eq!( |
| 595 | parse_concatenated_config_descriptors(&[0]).collect::<Vec<&[u8]>>(), |
| 596 | Vec::<&[u8]>::new() |
| 597 | ); |
| 598 | } |
| 599 | |
| 600 | #[test] |
| 601 | fn test_invalid_total_len() { |
| 602 | assert_eq!( |
| 603 | parse_concatenated_config_descriptors(&[9, 2, 0, 0, 0, 0, 0, 0, 0]) |
| 604 | .collect::<Vec<&[u8]>>(), |
| 605 | Vec::<&[u8]>::new() |
| 606 | ); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn test_one_config() { |
| 611 | assert_eq!( |
| 612 | parse_concatenated_config_descriptors(&[9, 2, 9, 0, 0, 0, 0, 0, 0]) |
| 613 | .collect::<Vec<&[u8]>>(), |
| 614 | vec![&[9, 2, 9, 0, 0, 0, 0, 0, 0]] |
| 615 | ); |
| 616 | |
| 617 | assert_eq!( |
| 618 | parse_concatenated_config_descriptors(&[9, 2, 13, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0]) |
| 619 | .collect::<Vec<&[u8]>>(), |
| 620 | vec![&[9, 2, 13, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0]] |
| 621 | ); |
| 622 | } |
| 623 | |
| 624 | #[test] |
| 625 | fn test_two_configs() { |
| 626 | assert_eq!( |
| 627 | parse_concatenated_config_descriptors(&[ |
| 628 | 9, 2, 13, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 9, 2, 9, 0, 0, 0, 0, 0, 0 |
| 629 | ]) |
| 630 | .collect::<Vec<&[u8]>>(), |
| 631 | vec![ |
| 632 | [9, 2, 13, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0].as_slice(), |
| 633 | [9, 2, 9, 0, 0, 0, 0, 0, 0].as_slice() |
| 634 | ] |
| 635 | ); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn test_empty_config() { |
| 641 | let c = Configuration(&[9, 2, 9, 0, 0, 1, 0, 0, 250]); |
| 642 | assert_eq!(c.num_interfaces(), 0); |
| 643 | assert_eq!(c.configuration_value(), 1); |
| 644 | assert_eq!(c.string_index(), None); |
| 645 | assert_eq!(c.interfaces().count(), 0); |
| 646 | } |
| 647 | |
| 648 | #[test] |
| 649 | fn test_malformed() { |
| 650 | let c = Configuration(&[9, 2, 0, 0, 0, 1, 0, 0, 2, 5, 250, 0, 0, 0]); |
| 651 | assert!(c.interfaces().next().is_none()); |
| 652 | } |
| 653 | |
| 654 | #[test] |
| 655 | #[rustfmt::skip] |
| 656 | fn test_linux_root_hub() { |
| 657 | let c = Configuration(&[ |
| 658 | 0x09, 0x02, 0x19, 0x00, 0x01, 0x01, 0x00, 0xe0, 0x00, |
| 659 | 0x09, 0x04, 0x00, 0x00, 0x01, 0x09, 0x00, 0x00, 0x00, |
| 660 | 0x07, 0x05, 0x81, 0x03, 0x04, 0x00, 0x0c |
| 661 | ]); |
| 662 | assert_eq!(c.num_interfaces(), 1); |
| 663 | assert_eq!(c.configuration_value(), 1); |
| 664 | assert_eq!(c.max_power(), 0); |
| 665 | assert_eq!(c.interfaces().count(), 1); |
| 666 | |
| 667 | let interface = c.interfaces().next().unwrap(); |
| 668 | assert_eq!(interface.interface_number(), 0); |
| 669 | |
| 670 | let mut alts = interface.alt_settings(); |
| 671 | |
| 672 | let alt = alts.next().unwrap(); |
| 673 | assert_eq!(alt.interface_number(), 0); |
| 674 | assert_eq!(alt.alternate_setting(), 0); |
| 675 | assert_eq!(alt.num_endpoints(), 1); |
| 676 | assert_eq!(alt.class(), 9); |
| 677 | assert_eq!(alt.subclass(), 0); |
| 678 | assert_eq!(alt.protocol(), 0); |
| 679 | assert_eq!(alt.endpoints().count(), 1); |
| 680 | |
| 681 | let endpoint = alt.endpoints().next().unwrap(); |
| 682 | assert_eq!(endpoint.address(), 0x81); |
| 683 | assert_eq!(endpoint.transfer_type(), EndpointType::Interrupt); |
| 684 | assert_eq!(endpoint.max_packet_size(), 4); |
| 685 | assert_eq!(endpoint.interval(), 12); |
| 686 | |
| 687 | assert!(alts.next().is_none()); |
| 688 | } |
| 689 | |
| 690 | #[test] |
| 691 | #[rustfmt::skip] |
| 692 | fn test_dell_webcam() { |
| 693 | let c = Configuration(&[ |
| 694 | 0x09, 0x02, 0xa3, 0x02, 0x02, 0x01, 0x00, 0x80, 0xfa, |
| 695 | |
| 696 | // unknown (skipped) |
| 697 | 0x28, 0xff, 0x42, 0x49, 0x53, 0x54, 0x00, 0x01, 0x06, 0x01, 0x10, 0x00, |
| 698 | 0x00, 0x00, 0x00, 0x00, 0xd1, 0x10, 0xd0, 0x07, 0xd2, 0x11, 0xf4, 0x01, |
| 699 | 0xd3, 0x12, 0xf4, 0x01, 0xd4, 0x13, 0xf4, 0x01, 0xd5, 0x14, 0xd0, 0x07, |
| 700 | 0xd6, 0x15, 0xf4, 0x01, |
| 701 | |
| 702 | // interface association |
| 703 | 0x08, 0x0b, 0x00, 0x02, 0x0e, 0x03, 0x00, 0x05, |
| 704 | |
| 705 | // interface |
| 706 | 0x09, 0x04, 0x00, 0x00, 0x01, 0x0e, 0x01, 0x00, 0x05, |
| 707 | |
| 708 | // VideoControl |
| 709 | 0x0d, 0x24, 0x01, 0x00, 0x01, 0x67, 0x00, 0xc0, 0xe1, 0xe4, 0x00, 0x01, 0x01, |
| 710 | |
| 711 | // VideoControl |
| 712 | 0x09, 0x24, 0x03, 0x05, 0x01, 0x01, 0x00, 0x04, 0x00, |
| 713 | |
| 714 | // VideoControl |
| 715 | 0x1a, 0x24, 0x06, 0x03, 0x70, 0x33, 0xf0, 0x28, 0x11, 0x63, 0x2e, 0x4a, |
| 716 | 0xba, 0x2c, 0x68, 0x90, 0xeb, 0x33, 0x40, 0x16, 0x08, 0x01, 0x02, 0x01, |
| 717 | 0x9f, 0x00, |
| 718 | |
| 719 | // VideoControl |
| 720 | 0x1a, 0x24, 0x06, 0x04, 0xc3, 0x85, 0xb8, 0x0f, 0xc2, 0x68, 0x47, 0x45, |
| 721 | 0x90, 0xf7, 0x8f, 0x47, 0x57, 0x9d, 0x95, 0xfc, 0x08, 0x01, 0x03, 0x01, |
| 722 | 0x0f, 0x00, |
| 723 | |
| 724 | // VideoControl |
| 725 | 0x12, 0x24, 0x02, 0x01, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, |
| 726 | 0x00, 0x00, 0x03, 0x0e, 0x00, 0x20, |
| 727 | |
| 728 | // VideoControl |
| 729 | 0x0b, 0x24, 0x05, 0x02, 0x01, 0x00, 0x00, 0x02, 0x7f, 0x17, 0x00, |
| 730 | |
| 731 | // Endpoint |
| 732 | 0x07, 0x05, 0x83, 0x03, 0x10, 0x00, 0x06, |
| 733 | |
| 734 | // Class-specific endpoint info |
| 735 | 0x05, 0x25, 0x03, 0x80, 0x00, |
| 736 | |
| 737 | // Interface |
| 738 | 0x09, 0x04, 0x01, 0x00, 0x00, 0x0e, 0x02, 0x00, 0x00, |
| 739 | |
| 740 | // Video Streaming |
| 741 | 0x0f, 0x24, 0x01, 0x02, 0x85, 0x01, 0x81, 0x00, 0x05, 0x00, 0x00, 0x00, |
| 742 | 0x01, 0x00, 0x00, |
| 743 | |
| 744 | // Video streaming |
| 745 | 0x0b, 0x24, 0x06, 0x01, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, |
| 746 | |
| 747 | // Video streaming (12 more omitted) |
| 748 | 0x06, 0x24, 0x0d, 0x01, 0x01, 0x04, |
| 749 | |
| 750 | // Interface |
| 751 | 0x09, 0x04, 0x01, 0x01, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 752 | |
| 753 | // Endpoint |
| 754 | 0x07, 0x05, 0x81, 0x05, 0x80, 0x00, 0x01, |
| 755 | |
| 756 | // Interface |
| 757 | 0x09, 0x04, 0x01, 0x02, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 758 | |
| 759 | // Endpoint |
| 760 | 0x07, 0x05, 0x81, 0x05, 0x00, 0x01, 0x01, |
| 761 | |
| 762 | // Interface |
| 763 | 0x09, 0x04, 0x01, 0x03, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 764 | |
| 765 | // Endpoint |
| 766 | 0x07, 0x05, 0x81, 0x05, 0x20, 0x03, 0x01, |
| 767 | |
| 768 | // Interface |
| 769 | 0x09, 0x04, 0x01, 0x04, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 770 | |
| 771 | // Endpoint |
| 772 | 0x07, 0x05, 0x81, 0x05, 0x20, 0x0b, 0x01, |
| 773 | |
| 774 | // Interface |
| 775 | 0x09, 0x04, 0x01, 0x05, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 776 | |
| 777 | // Endpoint |
| 778 | 0x07, 0x05, 0x81, 0x05, 0x20, 0x13, 0x01, |
| 779 | |
| 780 | // Interface |
| 781 | 0x09, 0x04, 0x01, 0x06, 0x01, 0x0e, 0x02, 0x00, 0x00, |
| 782 | |
| 783 | // Endpoint |
| 784 | 0x07, 0x05, 0x81, 0x05, 0x00, 0x14, 0x01 |
| 785 | ]); |
| 786 | |
| 787 | assert_eq!(c.configuration_value(), 1); |
| 788 | assert_eq!(c.num_interfaces(), 2); |
| 789 | assert_eq!(c.max_power(), 250); |
| 790 | |
| 791 | let mut interfaces = c.interfaces(); |
| 792 | let interface = interfaces.next().unwrap(); |
| 793 | assert_eq!(interface.interface_number(), 0); |
| 794 | let mut alts = interface.alt_settings(); |
| 795 | |
| 796 | let alt = alts.next().unwrap(); |
| 797 | assert_eq!(alt.interface_number(), 0); |
| 798 | assert_eq!(alt.alternate_setting(), 0); |
| 799 | assert_eq!(alt.num_endpoints(), 1); |
| 800 | assert_eq!(alt.class(), 14); |
| 801 | assert_eq!(alt.subclass(), 1); |
| 802 | assert_eq!(alt.protocol(), 0); |
| 803 | |
| 804 | let mut descriptors = alt.descriptors(); |
| 805 | assert_eq!(descriptors.next().unwrap().descriptor_type(), DESCRIPTOR_TYPE_INTERFACE); |
| 806 | for _ in 0..6 { |
| 807 | assert_eq!(descriptors.next().unwrap().descriptor_type(), 0x24); |
| 808 | } |
| 809 | assert_eq!(descriptors.next().unwrap().descriptor_type(), DESCRIPTOR_TYPE_ENDPOINT); |
| 810 | assert_eq!(descriptors.next().unwrap().descriptor_type(), 0x25); |
| 811 | assert!(descriptors.next().is_none()); |
| 812 | |
| 813 | let mut endpoints = alt.endpoints(); |
| 814 | |
| 815 | let endpoint = endpoints.next().unwrap(); |
| 816 | assert_eq!(endpoint.address(), 0x83); |
| 817 | assert_eq!(endpoint.transfer_type(), EndpointType::Interrupt); |
| 818 | assert_eq!(endpoint.max_packet_size(), 16); |
| 819 | |
| 820 | assert_eq!(endpoint.descriptors().nth(1).unwrap().descriptor_type(), 0x25); |
| 821 | |
| 822 | assert!(endpoints.next().is_none()); |
| 823 | assert!(alts.next().is_none()); |
| 824 | |
| 825 | let interface = interfaces.next().unwrap(); |
| 826 | assert_eq!(interface.interface_number(), 1); |
| 827 | let mut alts = interface.alt_settings(); |
| 828 | |
| 829 | let alt = alts.next().unwrap(); |
| 830 | assert_eq!(alt.interface_number(), 1); |
| 831 | assert_eq!(alt.alternate_setting(), 0); |
| 832 | assert_eq!(alt.num_endpoints(), 0); |
| 833 | assert_eq!(alt.class(), 14); |
| 834 | assert_eq!(alt.subclass(), 2); |
| 835 | assert_eq!(alt.protocol(), 0); |
| 836 | let mut endpoints = alt.endpoints(); |
| 837 | assert!(endpoints.next().is_none()); |
| 838 | |
| 839 | let alt = alts.next().unwrap(); |
| 840 | assert_eq!(alt.interface_number(), 1); |
| 841 | assert_eq!(alt.alternate_setting(), 1); |
| 842 | assert_eq!(alt.num_endpoints(), 1); |
| 843 | assert_eq!(alt.class(), 14); |
| 844 | assert_eq!(alt.subclass(), 2); |
| 845 | assert_eq!(alt.protocol(), 0); |
| 846 | let mut endpoints = alt.endpoints(); |
| 847 | |
| 848 | let endpoint = endpoints.next().unwrap(); |
| 849 | assert_eq!(endpoint.address(), 0x81); |
| 850 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 851 | assert_eq!(endpoint.max_packet_size(), 128); |
| 852 | |
| 853 | assert!(endpoints.next().is_none()); |
| 854 | |
| 855 | let alt = alts.next().unwrap(); |
| 856 | assert_eq!(alt.interface_number(), 1); |
| 857 | assert_eq!(alt.alternate_setting(), 2); |
| 858 | assert_eq!(alt.num_endpoints(), 1); |
| 859 | assert_eq!(alt.class(), 14); |
| 860 | assert_eq!(alt.subclass(), 2); |
| 861 | assert_eq!(alt.protocol(), 0); |
| 862 | let mut endpoints = alt.endpoints(); |
| 863 | |
| 864 | let endpoint = endpoints.next().unwrap(); |
| 865 | assert_eq!(endpoint.address(), 0x81); |
| 866 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 867 | assert_eq!(endpoint.max_packet_size(), 256); |
| 868 | assert_eq!(endpoint.packets_per_microframe(), 1); |
| 869 | |
| 870 | assert!(endpoints.next().is_none()); |
| 871 | |
| 872 | let alt = alts.next().unwrap(); |
| 873 | assert_eq!(alt.interface_number(), 1); |
| 874 | assert_eq!(alt.alternate_setting(), 3); |
| 875 | assert_eq!(alt.num_endpoints(), 1); |
| 876 | assert_eq!(alt.class(), 14); |
| 877 | assert_eq!(alt.subclass(), 2); |
| 878 | assert_eq!(alt.protocol(), 0); |
| 879 | let mut endpoints = alt.endpoints(); |
| 880 | |
| 881 | let endpoint = endpoints.next().unwrap(); |
| 882 | assert_eq!(endpoint.address(), 0x81); |
| 883 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 884 | assert_eq!(endpoint.max_packet_size(), 800); |
| 885 | assert_eq!(endpoint.packets_per_microframe(), 1); |
| 886 | |
| 887 | assert!(endpoints.next().is_none()); |
| 888 | |
| 889 | let alt = alts.next().unwrap(); |
| 890 | assert_eq!(alt.interface_number(), 1); |
| 891 | assert_eq!(alt.alternate_setting(), 4); |
| 892 | assert_eq!(alt.num_endpoints(), 1); |
| 893 | assert_eq!(alt.class(), 14); |
| 894 | assert_eq!(alt.subclass(), 2); |
| 895 | assert_eq!(alt.protocol(), 0); |
| 896 | let mut endpoints = alt.endpoints(); |
| 897 | |
| 898 | let endpoint = endpoints.next().unwrap(); |
| 899 | assert_eq!(endpoint.address(), 0x81); |
| 900 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 901 | assert_eq!(endpoint.max_packet_size(), 800); |
| 902 | assert_eq!(endpoint.packets_per_microframe(), 2); |
| 903 | |
| 904 | let alt = alts.next().unwrap(); |
| 905 | assert_eq!(alt.interface_number(), 1); |
| 906 | assert_eq!(alt.alternate_setting(), 5); |
| 907 | assert_eq!(alt.num_endpoints(), 1); |
| 908 | assert_eq!(alt.class(), 14); |
| 909 | assert_eq!(alt.subclass(), 2); |
| 910 | assert_eq!(alt.protocol(), 0); |
| 911 | let mut endpoints = alt.endpoints(); |
| 912 | |
| 913 | let endpoint = endpoints.next().unwrap(); |
| 914 | assert_eq!(endpoint.address(), 0x81); |
| 915 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 916 | assert_eq!(endpoint.max_packet_size(), 800); |
| 917 | assert_eq!(endpoint.packets_per_microframe(), 3); |
| 918 | |
| 919 | let alt = alts.next().unwrap(); |
| 920 | assert_eq!(alt.interface_number(), 1); |
| 921 | assert_eq!(alt.alternate_setting(), 6); |
| 922 | assert_eq!(alt.num_endpoints(), 1); |
| 923 | assert_eq!(alt.class(), 14); |
| 924 | assert_eq!(alt.subclass(), 2); |
| 925 | assert_eq!(alt.protocol(), 0); |
| 926 | let mut endpoints = alt.endpoints(); |
| 927 | |
| 928 | let endpoint = endpoints.next().unwrap(); |
| 929 | assert_eq!(endpoint.address(), 0x81); |
| 930 | assert_eq!(endpoint.transfer_type(), EndpointType::Isochronous); |
| 931 | assert_eq!(endpoint.max_packet_size(), 1024); |
| 932 | assert_eq!(endpoint.packets_per_microframe(), 3); |
| 933 | |
| 934 | assert!(endpoints.next().is_none()); |
| 935 | assert!(alts.next().is_none()); |
| 936 | assert!(interfaces.next().is_none()); |
| 937 | } |