Skip to main content

usb_stack/host/
descriptor.rs

1//! Parsing of the descriptors a device returns.
2//!
3//! Descriptors arrive as a flat byte string: the configuration descriptor is
4//! followed by its interface and endpoint descriptors, and class-specific
5//! descriptors may appear in between. Rather than copying them into a
6//! heap-allocated tree, [`Configuration`] keeps the bytes and lends out views
7//! over the parts that matter.
8
9use crate::descriptor::descriptor_type;
10use crate::endpoint::{EndpointAddress, EndpointType, IsoSynchronization, IsoUsage};
11use crate::host::error::{HostError, HostResult};
12
13#[inline]
14const fn le16(bytes: &[u8], offset: usize) -> u16 {
15    (bytes[offset] as u16) | ((bytes[offset + 1] as u16) << 8)
16}
17
18// ─── Device descriptor ───────────────────────────────────────────────────────
19
20/// The standard device descriptor (USB 2.0 §9.6.1).
21#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
22#[cfg_attr(feature = "defmt", derive(defmt::Format))]
23pub struct DeviceDescriptor {
24    /// `bcdUSB`.
25    pub usb_version: u16,
26    /// `bDeviceClass`.
27    pub class: u8,
28    /// `bDeviceSubClass`.
29    pub sub_class: u8,
30    /// `bDeviceProtocol`.
31    pub protocol: u8,
32    /// `bMaxPacketSize0`, the control endpoint packet size.
33    pub max_packet0: u16,
34    /// `idVendor`.
35    pub vendor_id: u16,
36    /// `idProduct`.
37    pub product_id: u16,
38    /// `bcdDevice`.
39    pub device_version: u16,
40    /// Manufacturer string index, zero when absent.
41    pub manufacturer: u8,
42    /// Product string index, zero when absent.
43    pub product: u8,
44    /// Serial number string index, zero when absent.
45    pub serial_number: u8,
46    /// `bNumConfigurations`.
47    pub configurations: u8,
48}
49
50impl DeviceDescriptor {
51    /// Length of the descriptor on the wire.
52    pub const LEN: usize = 18;
53
54    /// Parse the 18 bytes the device returned.
55    pub fn parse(bytes: &[u8]) -> HostResult<Self> {
56        if bytes.len() < Self::LEN || bytes[0] < Self::LEN as u8 {
57            return Err(HostError::Malformed);
58        }
59        if bytes[1] != descriptor_type::DEVICE {
60            return Err(HostError::Malformed);
61        }
62        Ok(Self {
63            usb_version: le16(bytes, 2),
64            class: bytes[4],
65            sub_class: bytes[5],
66            protocol: bytes[6],
67            max_packet0: bytes[7] as u16,
68            vendor_id: le16(bytes, 8),
69            product_id: le16(bytes, 10),
70            device_version: le16(bytes, 12),
71            manufacturer: bytes[14],
72            product: bytes[15],
73            serial_number: bytes[16],
74            configurations: bytes[17],
75        })
76    }
77}
78
79// ─── Raw descriptors ─────────────────────────────────────────────────────────
80
81/// One descriptor of a configuration, header included.
82#[derive(Clone, Copy, PartialEq, Eq, Debug)]
83pub struct Descriptor<'a> {
84    /// `bDescriptorType`.
85    pub kind: u8,
86    /// The whole descriptor, starting with its length and type bytes.
87    pub bytes: &'a [u8],
88}
89
90/// Iterates over the descriptors stored back to back in a configuration.
91#[derive(Clone, Copy, Debug)]
92pub struct Descriptors<'a> {
93    rest: &'a [u8],
94}
95
96impl<'a> Iterator for Descriptors<'a> {
97    type Item = Descriptor<'a>;
98
99    fn next(&mut self) -> Option<Self::Item> {
100        let length = *self.rest.first()? as usize;
101        if length < 2 || length > self.rest.len() {
102            // A truncated or zero-length descriptor: there is no sensible way
103            // to continue, so report the end of the list.
104            self.rest = &[];
105            return None;
106        }
107        let (head, tail) = self.rest.split_at(length);
108        self.rest = tail;
109        Some(Descriptor {
110            kind: head[1],
111            bytes: head,
112        })
113    }
114}
115
116// ─── Configuration ───────────────────────────────────────────────────────────
117
118/// A configuration descriptor together with everything that follows it.
119#[derive(Clone, Copy, PartialEq, Eq, Debug)]
120pub struct Configuration<'a> {
121    raw: &'a [u8],
122}
123
124impl<'a> Configuration<'a> {
125    /// Length of the configuration descriptor itself.
126    pub const HEADER_LEN: usize = 9;
127
128    /// Validate the bytes returned for `GET_DESCRIPTOR(CONFIGURATION)`.
129    pub fn parse(raw: &'a [u8]) -> HostResult<Self> {
130        if raw.len() < Self::HEADER_LEN || raw[1] != descriptor_type::CONFIGURATION {
131            return Err(HostError::Malformed);
132        }
133        let total = le16(raw, 2) as usize;
134        if total < Self::HEADER_LEN || total > raw.len() {
135            return Err(HostError::Malformed);
136        }
137        Ok(Self { raw: &raw[..total] })
138    }
139
140    /// Wrap bytes that were validated earlier: a previous [`parse`](Self::parse)
141    /// accepted them and nothing has changed since.
142    pub(crate) fn validated(raw: &'a [u8]) -> Self {
143        Self { raw }
144    }
145
146    /// The `wTotalLength` bytes of the configuration.
147    #[inline]
148    pub const fn bytes(&self) -> &'a [u8] {
149        self.raw
150    }
151
152    /// `wTotalLength`.
153    #[inline]
154    pub fn total_length(&self) -> u16 {
155        le16(self.raw, 2)
156    }
157
158    /// `bConfigurationValue`, the argument `SET_CONFIGURATION` expects.
159    #[inline]
160    pub fn value(&self) -> u8 {
161        self.raw[5]
162    }
163
164    /// `bmAttributes`.
165    #[inline]
166    pub fn attributes(&self) -> u8 {
167        self.raw[6]
168    }
169
170    /// `bMaxPower` in milliamperes (the descriptor stores 2 mA units).
171    #[inline]
172    pub fn max_power_ma(&self) -> u16 {
173        self.raw[8] as u16 * 2
174    }
175
176    /// Every descriptor in the configuration, in wire order.
177    #[inline]
178    pub fn descriptors(&self) -> Descriptors<'a> {
179        Descriptors { rest: self.raw }
180    }
181
182    /// The interfaces declared by the configuration.
183    #[inline]
184    pub fn interfaces(&self) -> Interfaces<'a> {
185        Interfaces {
186            raw: self.raw,
187            offset: Self::HEADER_LEN,
188        }
189    }
190
191    /// The first interface with the given class triple.
192    pub fn find_interface(&self, class: u8, sub_class: u8, protocol: u8) -> Option<Interface<'a>> {
193        self.interfaces()
194            .find(|i| i.class() == class && i.sub_class() == sub_class && i.protocol() == protocol)
195    }
196}
197
198// ─── Interface ───────────────────────────────────────────────────────────────
199
200/// An interface descriptor, with its endpoints following it in the raw bytes.
201#[derive(Clone, Copy, PartialEq, Eq, Debug)]
202pub struct Interface<'a> {
203    /// From the interface descriptor to the end of the configuration.
204    raw: &'a [u8],
205    /// Length of the interface descriptor itself.
206    length: usize,
207}
208
209impl<'a> Interface<'a> {
210    fn parse(bytes: &'a [u8]) -> Option<Self> {
211        if bytes.len() < 9 || bytes[1] != descriptor_type::INTERFACE {
212            return None;
213        }
214        Some(Self {
215            raw: bytes,
216            length: bytes[0] as usize,
217        })
218    }
219
220    /// `bInterfaceNumber`.
221    #[inline]
222    pub fn number(&self) -> u8 {
223        self.raw[2]
224    }
225
226    /// `bAlternateSetting`.
227    #[inline]
228    pub fn alternate_setting(&self) -> u8 {
229        self.raw[3]
230    }
231
232    /// `bNumEndpoints`, which is also the number of endpoints
233    /// [`endpoints`](Self::endpoints) yields unless the descriptor is truncated.
234    #[inline]
235    pub fn endpoint_count(&self) -> u8 {
236        self.raw[4]
237    }
238
239    /// `bInterfaceClass`.
240    #[inline]
241    pub fn class(&self) -> u8 {
242        self.raw[5]
243    }
244
245    /// `bInterfaceSubClass`.
246    #[inline]
247    pub fn sub_class(&self) -> u8 {
248        self.raw[6]
249    }
250
251    /// `bInterfaceProtocol`.
252    #[inline]
253    pub fn protocol(&self) -> u8 {
254        self.raw[7]
255    }
256
257    /// The endpoints of this interface.
258    ///
259    /// Class-specific descriptors end the list, exactly as the wire format
260    /// orders them.
261    #[inline]
262    pub fn endpoints(&self) -> Endpoints<'a> {
263        Endpoints {
264            rest: &self.raw[self.length.min(self.raw.len())..],
265        }
266    }
267}
268
269/// Iterates over the interfaces of a configuration.
270#[derive(Clone, Copy, Debug)]
271pub struct Interfaces<'a> {
272    raw: &'a [u8],
273    offset: usize,
274}
275
276impl<'a> Iterator for Interfaces<'a> {
277    type Item = Interface<'a>;
278
279    fn next(&mut self) -> Option<Self::Item> {
280        while self.offset + 2 <= self.raw.len() {
281            let start = self.offset;
282            let length = self.raw[start] as usize;
283            if length < 2 || start + length > self.raw.len() {
284                self.offset = self.raw.len();
285                return None;
286            }
287            self.offset += length;
288            if self.raw[start + 1] == descriptor_type::INTERFACE {
289                // An interface owns the descriptors that follow it, so hand out
290                // everything up to the end of the configuration.
291                return Interface::parse(&self.raw[start..]);
292            }
293        }
294        None
295    }
296}
297
298// ─── Endpoint ────────────────────────────────────────────────────────────────
299
300/// A standard endpoint descriptor (USB 2.0 §9.6.6).
301#[derive(Clone, Copy, PartialEq, Eq, Debug)]
302#[cfg_attr(feature = "defmt", derive(defmt::Format))]
303pub struct EndpointDescriptor {
304    /// `bEndpointAddress`: number and direction.
305    pub address: EndpointAddress,
306    /// `bmAttributes`.
307    pub attributes: u8,
308    /// `wMaxPacketSize` without the high-bandwidth bits.
309    pub max_packet: u16,
310    /// `bInterval`.
311    pub interval: u8,
312}
313
314impl EndpointDescriptor {
315    /// Length of the descriptor on the wire.
316    pub const LEN: usize = 7;
317
318    /// Parse seven bytes of an endpoint descriptor.
319    pub fn parse(bytes: &[u8]) -> HostResult<Self> {
320        if bytes.len() < Self::LEN || bytes[0] < Self::LEN as u8 {
321            return Err(HostError::Malformed);
322        }
323        if bytes[1] != descriptor_type::ENDPOINT {
324            return Err(HostError::Malformed);
325        }
326        Ok(Self {
327            address: EndpointAddress::from(bytes[2]),
328            attributes: bytes[3],
329            max_packet: le16(bytes, 4) & 0x07ff,
330            interval: bytes[6],
331        })
332    }
333
334    /// Transfer type encoded in `bmAttributes`.
335    pub fn transfer_type(&self) -> EndpointType {
336        match self.attributes & 0x03 {
337            0 => EndpointType::Control,
338            1 => EndpointType::Isochronous {
339                synchronization: IsoSynchronization::None,
340                usage: IsoUsage::Data,
341            },
342            2 => EndpointType::Bulk,
343            _ => EndpointType::Interrupt,
344        }
345    }
346}
347
348/// Iterates over the endpoints that follow an interface descriptor.
349#[derive(Clone, Copy, Debug)]
350pub struct Endpoints<'a> {
351    rest: &'a [u8],
352}
353
354impl Iterator for Endpoints<'_> {
355    type Item = EndpointDescriptor;
356
357    fn next(&mut self) -> Option<Self::Item> {
358        let length = *self.rest.first()? as usize;
359        if length < 2 || length > self.rest.len() || self.rest[1] != descriptor_type::ENDPOINT {
360            // Class-specific descriptors end the endpoint list.
361            self.rest = &[];
362            return None;
363        }
364        let (head, tail) = self.rest.split_at(length);
365        self.rest = tail;
366        EndpointDescriptor::parse(head).ok()
367    }
368}